Igo*_*ega 6 webpack webpack-dev-server
问题是Failed to load resource: the server responded with a status of 404 (Not Found)
当我使用webpack-dev-server时出现此错误。但是,如果我只是构建项目,则可以运行我的程序index.html
并获得预期的结果。我的项目结构是:
public/
index.html
assets/
src/
index.js
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
这是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')
}
}
Run Code Online (Sandbox Code Playgroud)
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' }
})
Run Code Online (Sandbox Code Playgroud)
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')
})
]
})
Run Code Online (Sandbox Code Playgroud)
因此,当我运行webpack-dev-server --open --config webpack.dev.js
CLI命令时,我得到了错误。当我跑步时webpack --config webpack.prod.js
,open index.html
一切都很好。我的问题是为什么webpack-dev-server的行为如此奇怪?我想念什么?
好的,问题解决了。就webpack-dev-server而言,实际上并没有在项目树中创建任何文件,而是将它们直接加载到内存中,这就是为什么我们不在bundle.js
文件assets
夹中获取文件的原因。接下来,我们devServer
在开发模式下使用它,并设置它的contentBase
属性来告诉服务器从何处提供内容。但是默认情况下,捆绑文件将在浏览器中可用,默认情况下publicPath
该文件在浏览器中/
。就我们assets
为此目的分配的目录而言,我们需要告诉webpack更改其默认值,并将其分配/assets/
给options的publicPath
属性devServer
。最后,下面是解决问题的代码:
在webpack.dev.js中
...
devServer: {
publicPath: "/assets/", // here's the change
contentBase: path.join(__dirname, 'public')
}
...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5962 次 |
最近记录: |