Search code examples
vue.jswebpackconfigurationbase64vue-cli

How to use base64-inline-loader in Vue CLI project to embed font files in CSS?


I am importing some custom font files into scss file for a vuejs project. When build, it creates these font-related files in /dist folder, along with app.js and app.css files. The files include font-name.ttf, font-name.woff, font-name.woff2 and font-name.svg

I want to embed these font files in app.css file as in base64 data uri when project build.


There is an npm package named base64-inline-loader and this seems to be a good choice for my problem.

The documentation of the package indicates a method of using it with webpack config. Since my project is using vue-cli 3 and vue-cli-service to run build commands, I know I need to use vue.config.js file to properly config base64-inline-loader.

I am not a big webpack expert and only knows basic concepts of it. I am having trouble in configuring the package in vue.config.js file. Hope there is somebody who already has some experience of using the same package preferably in Vue.js project.

Please provide me with the vue.config.js file that works :)


Solution

  • As seen from default Vue CLI webpack config, webpack processes font through url-loader:

    webpackConfig.module
      .rule('fonts')
      .test(/\.(woff2?|eot|ttf|otf)(\?.*)?$/i)
      .use('url-loader')
      .loader('url-loader')
      .options(genUrlLoaderOptions('fonts'))
    

    So first off you need to delete previous loaders applied to that rule, and set up needed(base64-inline-loader).

    module.exports = {
      chainWebpack: config => {
    
      const fontsRule = config.module.rule('fonts')
    
      // clear all existing loaders.
      // if you don't do this, the loader below will be appended to
      // existing loaders of the rule.
      fontsRule.uses.clear()
    
      config.module
        .rule('fonts')
        .test(/\.(ttf|otf|eot|woff|woff2)$/)
        .use('base64-inline-loader')
        .loader('base64-inline-loader')
        .tap(options => {
          // modify the options...    
          return options
         })
        .end()
      }
    }
    

    P.S. Helpful links:

    Related question.

    Replacing Loaders of a Rule.

    Adding a New Loader.