HtmlWebpackPlugin 注入相对路径文件,这些文件在加载非根网站路径时会中断

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 文件加载时,它会在不存在的 /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>

尝试在您的 webpack 配置中设置 publicPath:

output.publicPath = '/'

HtmlWebpackPlugin 使用 publicPath 来添加注入的 urls。

另一种选择是在 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/" />

应该这样做。