You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack Dev Server时无法找到data.json文件的问题排查

解决方法

问题原因

  1. Webpack Dev Server当前仅将public目录设为静态资源目录,model目录不在服务范围内,导致fetch无法访问data.json。
  2. 使用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文件到输出目录(推荐,适配生产环境)

  1. 安装copy-webpack-plugin:
npm install copy-webpack-plugin --save-dev
  1. 修改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: './' },
      ],
    }),
  ]
};
  1. 修改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,提问作者김석범

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:42:29