webpack开发服务器加载资源失败。

13
问题在于当我使用webpack-dev-server时,我会遇到这个错误:Failed to load resource: the server responded with a status of 404 (Not Found)。 但是如果我只构建项目,然后运行我的index.html,就可以得到预期的结果。 我的项目结构如下:
    public/
      index.html
      assets/
    src/
      index.js

index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>PBWA</title>
    </head>
    <body>
      <div id="root"></div>
    </body>
    <script src="assets/bundle.js"></script>
    </html>

这里是webpack配置文件

webpack.common.js

    const path = require('path')
    const CleanWebpackPlugin = require('clean-webpack-plugin')
    
    module.exports = {
      entry: './src/index.js',
      plugins: [
        new CleanWebpackPlugin(['assets'])
      ],
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'public/assets')
      }
    }

webpack.dev.js

    const merge = require('webpack-merge')
    const common = require('./webpack.common.js')
    
    module.exports = merge(common, {
      devtool: 'inline-source-map',
      devServer: { contentBase: './public' }
    })

webpack.prod.js

    const merge = require('webpack-merge')
    const common = require('./webpack.common.js')
    const webpack = require('webpack')
    const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
    
    module.exports = merge(common, {
      devtool: 'source-map',
      plugins: [
        new UglifyJSPlugin({ sourceMap: true }),
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('production')
        })
      ]
    })

所以当我运行 webpack-dev-server --open --config webpack.dev.js 命令时,我会收到错误信息。 而当我运行 webpack --config webpack.prod.js 然后运行 open index.html 一切都正常。 我的问题是为什么 webpack-dev-server 表现得如此奇怪?我错过了什么吗?


这里发生的情况是bundle.js没有生成。 - Igor Chernega
1个回答

16

好的,问题已经解决了。webpack-dev-server实际上不会在项目树中创建任何文件,而是直接将它们加载到内存中,这就是为什么我们在assets文件夹中没有得到bundle.js文件的原因。接下来,我们在开发模式下使用devServer,并设置它的contentBase属性,告诉服务器从哪里提供内容。但是默认情况下,捆绑文件将在浏览器中通过publicPath默认为/进行访问。既然我们已经将assets目录指定为这个目的,我们需要告诉webpack更改其默认值,并将/assets/指定为devServer选项的publicPath属性。 最后,以下代码可解决问题:

在webpack.dev.js中

...

devServer: {
  publicPath: "/assets/", // here's the change
  contentBase: path.join(__dirname, 'public')
}

...

2
你刚刚为我节省了很多时间!现在我把你当作我的朋友了。 - Stan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接