webpack dev server无法加载资源

时间:2017-11-24 16:42:10

标签: webpack webpack-dev-server

问题是当我使用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表现得那么奇怪?我错过了什么?

1 个答案:

答案 0 :(得分:5)

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

  webpack.dev.js中的

...

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

...
相关问题