2

Vue-cli has already configured url-loader to load base64 url encoded images for images smaller than 4kb. I need to load all images from a specific assets directory, let's say @/assets/img/pdf, as base64 to embed them into a pdfmake pdf.

I've already been trying to modify vue.config.js as described in documentation to edit the images rule but of course this impacts all images on the site and it's not what I want.

I tried to add a new rule to use url-loader on files from a single directory

module.exports = {
  chainWebpack: (config) => {
    config.module
      .rule('base64img')
      .test(/src\/assets\/img\/pdf\/(.*)\.+(png|jpe?g|gif)$/i)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 102400,
        fallback: { loader: 'file-loader' },
      })
      .end();
  },
};    

I import different images and add them to my template

import test1 from '@/assets/img/pdf/test1.png';
import test2 from '@/assets/img/pdf/test2.png';
import test3 from '@/assets/img/test3.png';

test3 is loaded as expected, but wierd things happen with test1 and test2. test1 (that is bigger than limit parameter) seems to be encoded with an unknown image

data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICI2YmUzZjE4YmY5OGM0ZTNjYWI2MzQxYWI5ZjhmNWJmNi5wbmciOw==

and test2 (smaller than limit parameter) seems to be loaded with fallback file-loader but with a wrong hash that is not displaying the image.

Totally opposite on what expected, however none of the two images is displayed.

markusand
  • 235
  • 7
  • 18

1 Answers1

2

First, to specify the assets location, you need to 'include' it instead of configuring it in the test regex.

Secondly, you need to add a new rule to the images rule for your desired path:

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

      .rule('images') // -> Custom rule specification
      .test(/\.(png|jpe?g|gif)$/)
      .include.add(/src\/assets\/img\/pdf\/.*/)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 102400,
        fallback: {
          loader: 'file-loader',
          options: { name: 'img/pdf/[name].[hash].[ext]' },
        },
      })
      .end()
  },
}

Configuring a name to the files exported in the dist folder by adding a name to options can be really helpful when debugging.

Also, you can run vue inspect --rule images in the console to check out the rule vue-cli is using and confirm the path is correct.

tokto
  • 116
  • 5