Webpack无法读取本地JSON文件问题求助
解决Webpack加载本地JSON文件的问题
问题根源
- file-loader使用错误:用file-loader处理JSON文件后,
require('./raw.json')得到的是文件的public路径字符串,而非JSON内容。后续试图把路径字符串当作JSON解析,导致报错。 - fs模块不可用:
fs是Node.js专属模块,浏览器环境不支持,前端代码里不能用fs.readFileSync读取文件。
解决方案
方案1:直接导入JSON内容(推荐,简单高效)
Webpack默认支持JSON文件导入,无需额外loader,直接就能拿到解析后的JS对象:
- 修改webpack.config.js:删除针对
.json的file-loader规则
module: { rules: [ { test: /\.html$/, use: ['html-loader'] }, { test: /\.js$/, enforce: "pre", use: ['source-map-loader'], }, // 移除JSON相关的file-loader规则 ], },
- 修改index.js:直接使用require返回的JSON对象,无需fetch
// 直接拿到解析后的JSON对象 const rawData = require('./assets/json/raw/raw.json'); // 示例:将数据渲染到HTML const container = document.getElementById('container'); for (const key in rawData) { const item = document.createElement('div'); item.innerHTML = `Key: ${key}, Val: ${rawData[key].val}, Val2: ${rawData[key].val2}`; container.appendChild(item); }
方案2:通过Fetch请求JSON文件(适合大文件/动态加载场景)
如果需要通过网络请求加载JSON(比如文件过大不想打包进JS),可以用file-loader将JSON文件复制到输出目录,再请求路径:
- 保留webpack.config.js的file-loader规则,确保JSON文件会被复制到输出目录
- 修改index.js:使用fetch请求require返回的文件路径
const jsonFilePath = require('./assets/json/raw/raw.json'); const fetchJSON = async () => { try { const response = await fetch(jsonFilePath); if (!response.ok) throw new Error('请求失败'); const data = await response.json(); console.log(data); // 这里添加渲染逻辑 } catch (error) { console.error('加载JSON出错:', error); } }; // 调用加载函数 fetchJSON();
注意:开发环境下Webpack Dev Server会自动处理路径;生产环境打包后,JSON文件会出现在输出目录的对应位置。
内容的提问来源于stack exchange,提问作者Preem Palver2
相关产品推荐
相关产品推荐

