Vite中动态读取JSON文件报错:Uncaught ReferenceError: require is not defined
Vite环境下重构动态读取JSON文件的函数
原函数与问题
原用于读取JSON文件的函数依赖CommonJS的require语法:
export function readFileFromDisk(file, folder) { // console.log(`Reading file ${file} from ${folder}`); let book = ""; if (typeof folder !== "undefined") { book = JSON.parse(JSON.stringify(require(`../data/${folder}/${file}`))); } else { book = JSON.parse(JSON.stringify(require(`../data/${file}`))); } return book; }
在Vite环境中运行时会报错:Uncaught ReferenceError: require is not defined。原因是Vite基于ES模块规范,不支持CommonJS的require,且ES模块的静态import语句无法在函数内部动态执行,需要重构函数适配Vite环境。
重构方案
方案一:预加载所有JSON文件(同步读取)
利用Vite提供的import.meta.glob批量预加载目标目录下的所有JSON文件,之后函数可同步返回数据:
// 预加载data目录下所有JSON文件(含子目录),eager设为true表示构建时加载 const jsonFiles = import.meta.glob('../data/**/*.json', { eager: true, import: 'default' }); export function readFileFromDisk(file, folder) { // 拼接对应文件的路径 const filePath = folder ? `../data/${folder}/${file}.json` : `../data/${file}.json`; // 获取预加载的JSON内容 const book = jsonFiles[filePath]; // 保留原函数的深拷贝逻辑,不需要可直接返回book return JSON.parse(JSON.stringify(book)); }
注:import: 'default'用于直接获取JSON文件的默认导出对象,省去额外的解构步骤。
方案二:动态导入(异步读取)
若不需要预加载全部文件,可使用ES模块的动态import(),但函数会变为异步:
export async function readFileFromDisk(file, folder) { const filePath = folder ? `../data/${folder}/${file}.json` : `../data/${file}.json`; // 动态导入目标文件 const module = await import(filePath); const book = module.default; // 保留深拷贝逻辑,不需要可直接返回book return JSON.parse(JSON.stringify(book)); }
调用示例:
// 使用.then()处理结果 readFileFromDisk('book1.json', 'novels').then(book => { console.log(book); }); // 或在async函数中用await调用 async function getTargetBook() { const book = await readFileFromDisk('book1.json'); console.log(book); }
内容的提问来源于stack exchange,提问作者jimmybondy
相关产品推荐
相关产品推荐

