webpack dev server 加载资源失败

webpack dev server Failed to load resource

问题是我在使用 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 CLI 命令时,我得到了错误。 当我 运行 webpack --config webpack.prod.js 然后 open index.html 一切正常。 我的问题是为什么 webpack-dev-server 的行为如此奇怪?我错过了什么?

好的,问题解决了。至于 webpack-dev-server 实际上并没有在项目树中创建任何文件,而是将它们直接加载到内存中,这就是为什么我们没有在 assets 文件夹中得到 bundle.js 文件。接下来我们在开发模式下使用 devServer 并将其设置为 contentBase 属性 以告知服务器从何处提供内容。但默认情况下,捆绑文件将在 publicPath 下的浏览器中可用,默认情况下为 /。就我们为此目的分配 assets 目录而言,我们需要告诉 webpack 更改它的默认值并将 /assets/ 分配给 publicPath 属性 或 devServer 选项。 最后,这是解决问题的代码:

in webpack.dev.js

...

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

...