webpack dev server 获取不到

Webpack dev server cannot get

我正在使用 Webpack-4。当前的行为是,当 webpack-dev-server 为 运行 时,/build 下的文件根本不会更新,它显示的是文件目录。

如果我删除/build下的文件,webpack-dev-server会报cannot get/。我想,它应该从内存中加载它们。

const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
   template: "./src/index.html",
   filename: "./index.html"
});

const path = require('path');

module.exports = {
output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build/'),
},

module: {
    rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: {
                loader: "babel-loader",
                options: {
                    presets: ["env","react"]
                }
            }
        },
        { 
            test: /\.html$/,
            use: [{
                loader: "html-loader",
                options: {
                    minimize: true
                }
            }]
        }
    ]
},
plugins: [
    htmlPlugin
],
devServer: {       
    contentBase: "./build/",
    port: 5555
}
}

一些帮助我理解和调试本地 webpack-dev-server 配置的技巧:

  1. 要查看 webpack-dev-server 提供文件的位置(内存中), 在浏览器中输入 http://localhost:{yourport}/webpack-dev-server。那么你就可以 单击其中一个文件 (link),它会向您显示它所服务的路线 来自和文件的内容。
  2. 当您启动 webpack-dev-server(即使用 npm start)时,它会在控制台中显示它根据您的 webpack.config.js 文件提供内容的位置。 (详细解释见下文)
  3. 如果你想要热重载(我不明白为什么不),你需要在命令行(在你的 package.json 启动脚本中)而不是在配置文件中指定它。出于某种原因,将它放入配置文件中是行不通的。所以使用类似的东西:

package.json

"scripts": {
    "start": "webpack-dev-server --config webpack.config.js --hot --inline"
},

webpack.config.js 配置

...
output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public', 'scripts'),
},
...
devServer: {
    contentBase: path.join(__dirname, "public"),
    publicPath: 'http://localhost:8080/scripts/',
    port: 8080
},
...

输出

 i 「wds」: Project is running at http://localhost:8080/    
 i 「wds」: webpack output is served from http://localhost:8080/scripts/
 i 「wds」: Content not from webpack is served from C:\Workspace\WebSite\public

在输出的第 2 行,请注意由于配置中的 contentBasehttp://localhost:8080/scripts/ 实际上指向磁盘上的 C:\Workspace\WebSite\public\scripts。 (这也是 webpack 放置文件的地方 :) !!!)

publicPath 配置中,结尾的反斜杠很重要。