我尝试使用 path、publicpath、contentBased 来解决这个问题,但没有成功。 (仅当 bundle.js 和 index.html 在同一文件夹中时才有效)
环境:Webpack 5 + webpack-dev-server + react。
问题:无法在 wp 开发服务器中正确加载应用程序,要么显示内容文件夹,要么不热重载。
如果在同一文件夹中生成 html 和包,这工作正常,但出于某种原因,我必须将它们保存在不同的文件夹中。
文件夹结构
dist\bundle.js
dist\style.css
public\index.html (generated by HTML-webpack-plugin)
public\.... (other files)
webpack 配置
output: {
path: path.resolve(..., 'dist') //also tried to generate dist inside public
filename: bundle.js
//publicPath: path.resolve(..., 'dist') //etc
}
devServer: {
contentBase: path.resolve(..., 'public')
}
我尝试了多种组合但没有运气, 我想保留 html 文件的单一版本,并且避免为开发构建手动修改 src。
有人可以指导正确的配置。
答案 0 :(得分:0)
contentBase
接受一个数组,如下所示:
module.exports = {
// ...
devServer: {
// ...
contentBase: [
path.join(RootPath, 'public'),
path.join(RootPath, 'dist')
]
// ...
}
// ...
};
需要注意的一件重要事情是 output.publicPath
在这里也起着至关重要的作用。
默认情况下(假设您的 target
是 web
(默认)或 webWorker
),output.publicPath
设置为 'auto'
,这意味着它确定url
根据您需要 bundle.js
的方式获取块。这在大多数情况下都可以正常工作。
但是,如果您的 bundle.js
本身是使用模糊的相对路径检索的(例如,OP 从 ../dist/bundle.js
检索它),那么 'auto'
将不起作用,您可能想要设置output.publicPath
手动,使用绝对路径(因为 OP 也最终这样做了)。