【发布时间】:2016-04-09 19:20:11
【问题描述】:
我正在使用 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文件加载完成后,会在不存在的/items目录下寻找js文件,因为react-router还没有加载。
如何让 HtmlWebpackPlugin 以绝对路径注入文件,所以 express 会在我的 /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>
【问题讨论】:
标签: javascript express webpack react-router