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

开发模式下运行demo目录index.html无法访问dist文件及自动刷新需求

解决Dev Server无法访问dist文件及自动刷新问题

问题根源

你当前的devServer只配置了demo作为静态资源目录,dist目录不在它的服务范围内,所以浏览器找不到里面的bundle.js。另外,要实现修改src后自动刷新,还得确保热替换的配置完全到位。

一步步解决

1. 让Dev Server同时托管Demo和Dist目录

根据你用的Webpack版本调整配置:

  • Webpack 5及以上:用static字段(替代旧版的contentBase),把两个目录都加进去
  • Webpack 4:直接把contentBase设为数组

修改后的webpack.dev.js关键部分:

const path = require('path');
const webpack = require('webpack'); // 别忘引入webpack

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
    publicPath: '/', // 这个配置没问题,保持不变
  },
  mode: 'development',
  devServer: {
    open: true,
    hot: true,
    // Webpack 5+ 用这个
    static: [
      path.resolve(__dirname, './demo'),
      path.resolve(__dirname, './dist')
    ],
    // Webpack 4 用这个,注释掉上面的static就行
    // contentBase: [
    //   path.resolve(__dirname, './demo'),
    //   path.resolve(__dirname, './dist')
    // ],
    port: 9000,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin() // 必须加这个插件,hot配置才会生效
  ]
  // ...其他原有配置
};

2. 确认HTML里的Bundle路径正确

在demo/index.html中,bundle.js的引用路径要和publicPath匹配,也就是写成:

<script src="/bundle.js"></script>

这样调整后,dev server就能正确找到dist/bundle.js了,而且修改src里的代码时,Hot Module Replacement会自动帮你刷新浏览器(甚至局部重载,不用全页刷新)。

内容的提问来源于stack exchange,提问作者vciloglu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:49