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

JavaScript Webpack

LEY宝儿神奇

2020-03-23

我正在使用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>

第2680篇《HtmlWebpackPlugin注入相对路径文件,该路径文件在加载非根网站路径时会中断》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
蛋蛋猿 2020.03.23

在webpack配置中

config.output.publicPath = ''

在您的index.html中

<base href="/someurl/" />

这应该做到。

番长猴子 2020.03.23

尝试在webpack配置中设置publicPath:

output.publicPath = '/'

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

另一种选择是在<head>html模板的中设置基本href ,以指定文档中所有相对URL的基本URL。

<base href="http://localhost:3000/">

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android