使用Webpack Dev Server时无法找到data.json文件的问题排查
解决方法
问题原因
- Webpack Dev Server当前仅将
public目录设为静态资源目录,model目录不在服务范围内,导致fetch无法访问data.json。 - 使用
mode: 'no-cors'会让响应变为不透明类型,无法调用res.json()解析数据。
方案一:扩展Dev Server的静态资源目录
修改webpack.config.js里的devServer.static配置,把model目录加入静态资源服务范围:
devServer: { static: [ { directory: path.join(__dirname, 'public') }, { directory: path.join(__dirname, 'model') } ], compress: true, port: 9000, },
然后修改index.js中的fetch路径,直接请求根路径下的data.json:
fetch('/data.json') .then(function (res) { return res.json(); }) .then(function (data) { console.log(data); });
方案二:复制JSON文件到输出目录(推荐,适配生产环境)
- 安装
copy-webpack-plugin:
npm install copy-webpack-plugin --save-dev
- 修改
webpack.config.js,引入插件并配置复制规则:
const path = require("path"); const HtmlWebPackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyPlugin = require('copy-webpack-plugin'); // 新增 module.exports = { // 其他原有配置不变 plugins: [ new HtmlWebPackPlugin({ template: './public/index.html', filename: 'index.html' }), new MiniCssExtractPlugin({ filename: 'style.css' }), new CleanWebpackPlugin(), new CopyPlugin({ // 新增复制规则 patterns: [ { from: './model/data.json', to: './' }, ], }), ] };
- 修改
index.js中的fetch路径为根路径:
fetch('/data.json') .then(function (res) { return res.json(); }) .then(function (data) { console.log(data); });
方案三:直接导入JSON文件(无需fetch)
如果JSON文件不需要动态加载,可直接通过import引入,Webpack会自动将其打包到bundle中:
import './favicon.ico'; import data from '../model/data.json'; console.log(data);
这种方式无需配置静态资源或复制插件,简单高效。
内容的提问来源于stack exchange,提问作者김석범
相关产品推荐
相关产品推荐

