gpt4 book ai didi

webpack开发服务器无法加载资源

转载 作者:行者123 更新时间:2023-12-04 11:47:32 24 4
gpt4 key购买 nike

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

in webpack.dev.js


...

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

...

关于webpack开发服务器无法加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com