插件窝 干货文章 Vue 3 Vite项目如何动态读取public目录下的文件?

Vue 3 Vite项目如何动态读取public目录下的文件?

文件 使用 读取 目录 803    来源:    2025-03-19

在Vue 3 Vite项目中,public目录下的文件会被直接复制到构建输出目录中,并且可以通过根路径访问。如果你想动态读取public目录下的文件,可以使用以下几种方法:

方法1:使用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);
  });
}

方法2:使用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);
  });

方法3:使用axiosXMLHttpRequest

你也可以使用 axiosXMLHttpRequest 来动态读取 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();

方法4:使用vite-plugin-static-copy插件

如果你需要更复杂的文件处理逻辑,可以使用 vite-plugin-static-copy 插件来复制文件到指定目录,并在代码中动态读取。

  1. 安装插件:
npm install vite-plugin-static-copy --save-dev
  1. 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'
        }
      ]
    })
  ]
});
  1. 在代码中动态读取文件:
const files = import.meta.glob('/assets/*.json');

for (const path in files) {
  files[path]().then((module) => {
    console.log(module.default);
  });
}

总结

  • 如果你只需要读取少量文件,使用 fetchaxios 是最简单的方法。
  • 如果你需要动态导入多个文件,可以使用 import.meta.glob
  • 如果你需要更复杂的文件处理逻辑,可以考虑使用 vite-plugin-static-copy 插件。

根据你的具体需求选择合适的方法即可。