【问题标题】:HtmlWebpackPlugin injects relative path files which breaks when loading non-root website pathsHtmlWebpackPlugin 注入在加载非根网站路径时会中断的相对路径文件
【发布时间】: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


    【解决方案1】:

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

    output.publicPath = '/'
    

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

    另一种选择是在您的 html 模板的 &lt;head&gt; 中设置基本 href,以指定文档中所有相对 url 的基本 url。

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

    【讨论】:

    • 谢谢,添加output.publicPath = '/' 是解决方案。
    • 如果你在反向代理后面运行,这将不起作用。
    • 您也可以简单地使用&lt;base href="/"&gt; 来避免在 HTML 模板中硬编码主机名,或插入变量。
    • 我必须设置 publicPath = '' 并添加 因为我的网站是一个使用 IIS 和虚拟目录的 ASP.Net MVC 项目。
    • 引导我走向正确的方向。将publicPath 设置为""(一个空字符串)可以解决我的问题。
    【解决方案2】:

    其实我不得不说:

    output.publicPath: './';
    

    为了让它在非ROOT路径中工作。 同时我在注射:

       baseUrl: './'
    

    进入

    <base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">
    

    设置了这两个参数,它就像一个魅力。

    【讨论】:

    • 这将浏览器上的URL 显示为https://localhost/myproject/%3C%=%20htmlWebpackPlugin.options.baseUrl%20%%3E#/project/1。有没有办法解决这个问题?
    • 你在哪里设置 baseUrl: '.' 是在 HtmlWebpackPlugin 选项中吗? { meta: { baseUrl: './' } }?
    • @SomethingOn 我现在手头没有这个 webpack 项目,而且我认为自从我发布这个答案(包括默认值)以来,很多事情都发生了变化。所以是的,这当然是应该设置的地方,但'./' 是正确的值。
    • 现在可以直接注入base tag了。 inject base tag
    • 愚蠢但非常有效的第二种方法。谢谢!
    【解决方案3】:

    在 webpack 配置中

    config.output.publicPath = ''
    

    在你的 index.html 中

    <base href="/someurl/" />
    

    应该这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 2013-03-05
      • 2021-09-15
      • 1970-01-01
      • 2023-04-01
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多