webpack-dev-server 在保存文件时不更新包

webpack-dev-server not updating bundle when saving file

我正在从头开始自学 webpack,当我在我的应用程序文件中更改 .js 并显示更改时,我正在尝试使用 webpack-dev-server 实时更新浏览器。假设我有以下 package.json

{
  "name": "webpack-babel",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "serve": "webpack-dev-server --hot",
    "start": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-preset-es2015": "^6.22.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }
}

这是我的 webpack.config.json

const path = require('path');

    const config = {
        entry: './app/index.js',
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015']
                    }
                }
            ],
        }
    };

    module.exports = config;

我的 ./app/index.js 中有以下代码(这里没什么特别的):

let message = 'I love socks and snacks !';
console.log(message);

当我 运行 npm run serveapp/index.js 中的消息更改为 'I love cola and snacks !!!' 并保存时,终端确实可以编译,但浏览器中没有任何更新。捆绑文件仍包含旧消息并且未生成。我究竟做错了什么?我几个小时前才开始尝试这个,所以我是 webpack 的新手。

我在 IDE 中关闭了“安全写入”,我的文件结构如下:

这是我的 index.html...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script src="dist/bundle.js"></script>
</body>

* 更新 * 将 publicPath: 'dist/' 添加到 output 对象似乎有效...但我不确定这是否正确解决我的问题。

The bundle file still contains the old message and isn't being generated.

webpack-dev-server 不创建任何文件,而是在命中相应路径时从内存中提供包。默认情况下这是 /,因此当您尝试加载 /bundle.js 时,您将从内存中获取包。

但是在您的 index.html 中您请求 /dist/bundle.js。它首先可以找到它的唯一原因是因为您生成了它并且它实际上存在于您的文件系统中。要明确,如果你去:

http://localhost:8080/dist/bundle.js

您从您的文件系统中获取了捆绑包,但是当您转到:

http://localhost:8080/bundle.js

您通过 webpack-dev-server 从内存中获取了包,尽管它不存在于您的文件系统中。

正如您正确检查的那样,您可以使用 publicPath 选项更改该路径。因此设置 publicPath: '/dist/' 将使 webpack-dev-server 在点击 /dist/bundle.js 时从内存中提供包,无论该文件是否存在于您的文件系统中。

改为设置 output.publicPath also affects some loaders that include assets, as seen in the example of html-loader. If you don't desire that effect, you can use devServer.publicPath,以仅更改 webpack-dev-server 的行为。但正如文档中所述,建议它们相同。

根据最新的 webpack DOC,devServer 配置应该是这样的。

devServer: {
  static: './dist/',
  hot: true,
  devMiddleware: {
      publicPath: '/dist/',
      writeToDisk: true,
   },    
 }