ahe*_*iot 99 javascript express webpack react-router
我使用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)
小智 174
尝试在webpack配置中设置publicPath:
output.publicPath = '/'
Run Code Online (Sandbox Code Playgroud)
HtmlWebpackPlugin使用publicPath来预先注入注入的url.
另一种选择是在<head>
html模板中设置基本href ,以指定文档中所有相对URL的基本URL.
<base href="http://localhost:3000/">
Run Code Online (Sandbox Code Playgroud)
Kev*_*INE 12
事实上,我不得不说:
output.publicPath: './';
Run Code Online (Sandbox Code Playgroud)
为了让它在非ROOT路径下工作.同时我注射:
baseUrl: './'
Run Code Online (Sandbox Code Playgroud)
成
<base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">
Run Code Online (Sandbox Code Playgroud)
有了这两个参数设置,它就像一个魅力.
在 webpack 配置中
config.output.publicPath = ''
Run Code Online (Sandbox Code Playgroud)
在你的 index.html
<base href="/someurl/" />
Run Code Online (Sandbox Code Playgroud)
这应该这样做。