在Vue 3 Vite项目中,public
目录下的文件会被直接复制到构建输出目录中,并且可以通过根路径访问。如果你想动态读取public
目录下的文件,可以使用以下几种方法:
import.meta.glob
Vite 提供了 import.meta.glob
功能,可以动态导入文件。你可以使用它来动态读取 public
目录下的文件。
// 假设你想读取 public 目录下的所有 JSON 文件
const files = import.meta.glob('/public/*.json');
for (const path in files) {
files[path]().then((module) => {
console.log(module.default);
});
}
fetch
API由于 public
目录下的文件会被直接复制到根目录,你可以使用 fetch
API 来动态读取这些文件。
// 假设你想读取 public 目录下的 example.json 文件
fetch('/example.json')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching the file:', error);
});
axios
或 XMLHttpRequest
你也可以使用 axios
或 XMLHttpRequest
来动态读取 public
目录下的文件。
// 使用 axios
import axios from 'axios';
axios.get('/example.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching the file:', error);
});
// 使用 XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', '/example.json', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
vite-plugin-static-copy
插件如果你需要更复杂的文件处理逻辑,可以使用 vite-plugin-static-copy
插件来复制文件到指定目录,并在代码中动态读取。
npm install vite-plugin-static-copy --save-dev
vite.config.js
中配置插件:import { defineConfig } from 'vite';
import { viteStaticCopy } from 'vite-plugin-static-copy';
export default defineConfig({
plugins: [
viteStaticCopy({
targets: [
{
src: 'public/*.json',
dest: 'assets'
}
]
})
]
});
const files = import.meta.glob('/assets/*.json');
for (const path in files) {
files[path]().then((module) => {
console.log(module.default);
});
}
fetch
或 axios
是最简单的方法。import.meta.glob
。vite-plugin-static-copy
插件。根据你的具体需求选择合适的方法即可。