我使用webpack和HtmlWebpackPlugin将捆绑的js和css注入到html模板文件中.
new HtmlWebpackPlugin({
template: 'client/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
Run Code Online (Sandbox Code Playgroud)
它会生成以下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>
Run Code Online (Sandbox Code Playgroud)
这在访问应用程序的根目录时工作正常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'));
});
Run Code Online (Sandbox Code Playgroud)
基本上,我只需要得到这条线:
<script src="main...js"></script>
Run Code Online (Sandbox Code Playgroud)
在源的开头有一个斜杠.
<script src="/main...js></script>
Run Code Online (Sandbox Code Playgroud)