[英]HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths
我使用webpack和HtmlWebpackPlugin将捆绑的js和css注入到html模板文件中。
new HtmlWebpackPlugin({
template: 'client/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
它会生成以下html文件。
<!doctype html>
<html lang="en">
<head>
...
<link href="main-295c5189923694ec44ac.min.css" rel="stylesheet">
</head>
<body>
<div id="app"></div>
<script src="main-295c5189923694ec44ac.min.js"></script>
</body>
</html>
这在访问应用程序localhost:3000/
的根目录时工作正常,但在我尝试从另一个URL访问应用程序时失败,例如localhost:3000/items/1
因为捆绑的文件未注入绝对路径。 加载html文件时,它将在non-exist /items
目录中查找js文件,因为react-router尚未加载。
如何让HtmlWebpackPlugin注入具有绝对路径的文件,所以express会在my /dist
目录的根目录而不是/dist/items/main-...min.js
? 或者也许我可以更改我的快速服务器来解决这个问题?
app.use(express.static(__dirname + '/../dist'));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
基本上,我只需要得到这条线:
<script src="main...js"></script>
在源的开头有一个斜杠。
<script src="/main...js></script>
尝试在webpack配置中设置publicPath:
output.publicPath = '/'
HtmlWebpackPlugin使用publicPath来预先注入注入的url。
另一个选项是在html模板的<head>
中设置基本href,以指定文档中所有相对URL的基本URL。
<base href="http://localhost:3000/">
事实上,我不得不说:
output.publicPath: './';
为了让它在非ROOT路径下工作。 同时我注射:
baseUrl: './'
成
<base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">
有了这两个参数设置,它就像一个魅力。
在webpack配置中
config.output.publicPath = ''
在index.html中
<base href="/someurl/" />
这应该做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.