如何更改 webpack 构建中的所有 href 和 src 路径?

How to change all href and src paths on webpack building?

我有一个网站,主要用 pug(html 预处理器)编写。我使用 output.publicPath 等于 '/' 这样我就可以 运行 webpack 在开发模式下轻松工作,将项目文件夹视为根目录,但每个 href、src 和 url 都是绝对的小路。当我构建项目时,我想通过在开始时添加一些节点(让我们使用'/path/to/')来改变每条路径。比如我有一张图片

img(src="/img/image.jpg")

在我构建这个项目之后,我想收到这个:

<img src="/path/to/img/image.jpg">

并通过 hrefs 和 urls 接收相同的内容。

我制作了一个 webpack 构建配置并将 output.publicPath 设置为 '/path/to/' 但它更改了链接 css 和 js 文件的路径:

mode: "production",
  output: {
  publicPath: "/HTMLPractice/dist/"
}

我很高兴收到任何解决方案、想法或建议。

您可以在 file-loader 上设置 publicPath,只要 file-loader 正则表达式包含图像文件即可。

在您的 webpack.config.js 规则中:

     {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: 'some/path',
        },
      },

更多信息:https://webpack.js.org/loaders/file-loader/#publicpath