Webpack 开发服务器在热时重新编译但包实际上并没有改变

Thi*_*aku 1 webpack webpack-dev-server

我正在使用 webpack 来测试我正在编写的代码生成库的输出:https : //github.com/Neone-character-creator/app-generator/blob/master/project-template/webpack.config.js

该库将文件复制到一个新目录中,然后 webpack 为它们提供服务。

最终结果会将 Web 应用程序打包为注入服务器的 Java jar,前端将选择它应该显示的内容并将其嵌入到 iframe 中。我试图模拟这一点,我在其中显示 demo.html,其中包含一个加载 的 iframe,sheet.html加载app.bundle.js.

当开发服务器正在运行并且我更改了一些文件并重新调用库时,更新的文件被移动到位,在控制台中我可以看到 webpack 执行重新编译。

然而,当我查看编译后的包时,它实际上并没有改变,即使包的源文件不同。我必须重新启动服务器才能使包真正更新。

const path = require("path");

module.exports = {
    "mode": "development",
    "entry": "./src/main/resources/scripts/app.js",
    "output" : {
        path: path.resolve(__dirname, "src/main/resources/scripts/"),
        filename: "app.bundle.js",
        publicPath: "/src/main/resources"
    },
    devServer:{
        before: function(app, server){
            app.use("/templates/sheet.html", function(req, res) {
                const resourcePath = path.resolve(__dirname + "/src/main/resources" + req.baseUrl);
                res.sendFile(resourcePath);
            });
            app.use(/\/scripts\/.*/, function(req, res) {
                const resourcePath = path.resolve(__dirname + "/src/main/resources" + req.baseUrl);
                res.sendFile(resourcePath);
            });
        },
        contentBase: __dirname,
        port: 9999,
        hot: true,
        index: "demo.html",
        historyApiFallback: {
            index: "demo.html",
        }
    },
    "module": {
        "rules": [
            {
                "test": /\.(js|jsx)$/,
                "exclude": /node_modules/,
                "use": {
                    "loader": "babel-loader",
                    "options": {
                        "presets": [
                            "@babel/env",
                            "@babel/react"
                        ]
                    }
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ]
    },
}
Run Code Online (Sandbox Code Playgroud)

HotModuleReplacementPluginwebpack 配置添加和--hot--inline标志到 dev-server 命令不起作用。

for*_*d04 6

这里可能会发生以下情况:

我认为,您通过npm start位于存储库 package.json 中的脚本启动开发服务器。此脚本执行初始完整构建,webpack-cli将包输出到您的目标目录。如果构建成功,它会webpack-dev-server在源更改时通过命令重新编译包来监视所有源文件。

问题是:webpack-cli将写入磁盘,webpack-dev-server默认情况下会在开发过程中出于性能原因在内存中构建包:

webpack-dev-server 编译后不写入任何输出文件。相反,它将捆绑文件保存在内存中,并将它们视为安装在服务器根路径上的真实文件。

如此有效地您将一次写入磁盘,然后在文件系统中有一个陈旧的包,而开发服务器编译更改并通过内存提供服务。

如果我理解正确,您依赖于将编译后的包输出写入文件,因此您可以进一步将包/webapp 打包为服务器的 Java jar。如果你仍然想使用 webpack-dev-server 来利用 web 服务器和使用实时重新加载的能力,有一个devServer.writeToDisk选项,可以启用(默认值:false):

webpack.config.js:

module.exports = {
  //...
  devServer: {
    writeToDisk: true
  }
};
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以使用 Webpack 的监视模式来重新编译,如果其中一个文件被更新,则您不必手动构建。

包.json:

"scripts": {
  //...
  "watch": "webpack --watch"
}
Run Code Online (Sandbox Code Playgroud)