How to load a font file in vuejs and webpack?

Put your fonts in the public/fonts/ folder. In css or scss, specify the path starting with /fonts/.

Example scss:

$font-dir: "/fonts/";

@font-face {
  font-family: "NameFont";
  src: url("#{$font-dir}NameFontRegular/NameFontRegular.eot");
  src: url("#{$font-dir}NameFontRegular/NameFontRegular.eot?#iefix")format("embedded-opentype"),
  url("#{$font-dir}NameFontRegular/NameFontRegular.woff") format("woff"),
  url("#{$font-dir}NameFontRegular/NameFontRegular.ttf") format("truetype");
  font-style: normal;
  font-weight: normal;
}

Next, import your scss into main.js

Example:

// eslint-disable-next-line
import styles from './assets/scss/main.scss';

or in vue.config.js

Example:

module.exports = {
...
  css: {
    modules: true,
    loaderOptions: {
      css: {
        localIdentName: '[name]-[hash]',
        camelCase: 'only'
      },
      sass: {
        data: '@import "~@/assets/scss/import/_variables.scss"; @import "~@/assets/scss/import/_mixins.scss";'
      },
    },
  },
...
}

It's a webpack error. You are missing a webpack loader to manage font files. Usually I use file-loader for fonts:

{
  test: /\.(ttf|otf|eot|woff|woff2)$/,
  use: {
    loader: "file-loader",
    options: {
      name: "fonts/[name].[ext]",
    },
  },
}

Add this code in your webpack config file (module > rules section) or if you're using vue-cli 3, in your vue.config.js file (configurewebpack section).


Hope this will help others who are facing the same issue. For some reason Vue.js is giving error when using .otf files. I used .woff and now everything works fine. Use the following code in your webpack.config.js file :

      module.exports = function (config, { isClient, isDev }) {
            module: { rules: [ { test: /\.(woff|woff2|eot|ttf|svg)(\?.*$|$)/, 
            loader: 'file-loader' } ] }
            return config }

and import the files in your css file using something like this

 @font-face { 
       font-family: "Questrial";
       src: url("../../fonts/Questrial-Regular.ttf"); 
   }