首页 文章

使用Webpack生成具有相对资产路径的HTML

提问于
浏览
1

我有以下src文件夹结构:

/src
+-- /app
|   +-- index.js
|   +-- /templates
|       +-- index.html
|       +-- /subfolder
|           +-- nested.html
|
+-- /images
|   +-- webpack.png
| 
+-- /styles
|   +-- index.scss

我正在尝试使用app文件夹中的模板配置webpack以发出多个html文件 . 最终的构建文件夹结构应如下所示:

/build
+-- /images
|   +-- webpack.png
|
+-- /subfolder
|   +-- nested.html
|
+-- index.html
+-- bundle.js
+-- styles.css

问题是在构建之后, index.htmlnested.html 具有相同的图像路径 <img src="img/webpack.png"> ,这对于 nested.html 是不正确的

nested.html 应该有以下路径 - <img src="../img/webpack.png"> .

如何让webpack为嵌套的html文件设置正确的资源路径?


Steps to reproduce.

  • 下载repo

  • 安装包 npm install

  • 运行 npm run build

my webpack.config.js

my package.json

根据这个线程,它不是html-loader的问题 - https://github.com/webpack-contrib/file-loader/issues/272

Webpack文档提到组件之间的资产共享但没有提供示例 - https://webpack.js.org/guides/asset-management/#global-assets

html-loader选项可能有一个解决方案,但文档没有't make much sense to me and I can' t弄明白 - https://webpack.js.org/guides/asset-management/#global-assets

第一条动态生成htmlWebpackPlugin - https://extri.co/2017/07/11/generating-multiple-html-pages-with-htmlwebpackplugin/

1 回答

  • 0

    今天早上我又看了一眼,我有办法做你想做的事,虽然它并不完美 .

    如果将图像文件夹移动到模板文件夹中,并在HTML SCSS中更新您的网址以进行匹配 .

    更改映像的文件加载程序设置,以便将它们放在与源目录同名的目录中 .

    ...
      {
        loader: "file-loader",
        options: {
          name: "[name].[ext]",
          // outputPath: "img/" 
          // Use same name as source
          outputPath: "images/" 
        }
      }
      ...
    

    向walk函数添加一个测试,以便它只包含模板目录中的html文件,这样我们就不会在尝试使用HtmlWebpackPlugin处理图像时出错 .

    ...
      if (isDirectory) {
            // File is a directory
            ... code ...
          } else if (/\.html$/.test(file)) {
            ... code ...
          }
      ...
    

    并删除html-loader,因为它正在重写图像URL,打破了它们的相对路径 .

    通过这些更改,Webpack将保留img标记中的相对URL . 它还将为您的构建目录中的工作创建正确的结构 . 这些图像也可以在CSS中工作,从构建/根目录加载的整个时间也是如此 .

    这不是一个完美的解决方案,它可以像Webpack中的许多其他东西一样自动工作 . 但它应该完成你现在想要的,至少在你找到更好的方法之前 .

相关问题