Is there a way to disable filenameHashing only for specific resources (images) in webpack?

故事扮演 提交于 2019-12-04 17:10:18

Yes, there is a way. You will need to override the 'images' rule that vue-cli comes with.

vue inspect --rule images yields the following:

$ vue inspect --rule images
/* config.module.rule('images') */
{
  test: /\.(png|jpe?g|gif|webp)(\?.*)?$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 4096,
        fallback: {
          loader: 'file-loader',
          options: {
            name: 'img/[name].[hash:8].[ext]'
          }
        }
      }
    }
  ]
}

(Protip: vue inspect is a useful tool for figuring out why things behave like they do when building with vue-cli)

All images

vue-cli recommends webpack-chain for 'advanced' configuration. I'm personally not a fan, but if you want to remove hashes for all images, you should probably modify the 'images' rule. Edit vue.config.js like so:

module.exports = {
  // ...
  chainWebpack: (config) => {
    config.module
      .rule("images")
      .use("url-loader")
      .loader("url-loader")
      .tap((options) => {
        options.fallback.options.name = "img/[name].[ext]"
        return options
      })
  }
  // ...
}

Specific images

In my case I wanted to remove hashes only for a specific group of images with a unique prefix, so I added the following to configureWebpack in vue.config.js:

module.exports = {
  // ...
  configureWebpack: {
    module: {
      rules: [
        {
          test: /unique-prefix-\d*\.png/, // <= modify this to suit your needs
          use: [
            {
              loader: "url-loader",
              options: {
                limit: 4096,
                fallback: {
                  loader: "file-loader",
                  options: {
                    name: "img/[name].[ext]", // <= note how the hash is removed
                  },
                },
              },
            },
          ],
        },
      ],
    },
  // ...
}

It could probably be done with webpack-chain as well, but I prefer the more vanilla Webpack config format.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!