How do I add a Google Font to a VueJS Component?

Solution 1:

The fastest way is to import the font in a CSS file, for example App.css, if all components should have it:

@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed');

html, body {
  font-family: 'Roboto', sans-serif;
}

#app {
  font-family: 'Roboto', sans-serif;
}

The import statement is also shown by Google Fonts.

Select your fonts, click on Embed and then @import at the selection window:

Google Fonts

Solution 2:

Imo, if you're using VueJS, Google Fonts Webpack Plugin is the way.

Here's the plugin, it's really easy to set it up and works like a charm.

npm i google-fonts-webpack-plugin -D

Go to your /webpack.config.js / webpack.base.config.js and add the following lines:

const GoogleFontsPlugin = require("google-fonts-webpack-plugin")

module.exports = {
    "entry": "index.js",
    /* ... */
    plugins: [
        new GoogleFontsPlugin({
            fonts: [
                { family: "Source Sans Pro" },
                { family: "Roboto", variants: [ "400", "700italic" ] }
            ]
        })
    ]
}

Now you can use Google Fonts anywhere inside your VueJS project :)

Solution 3:

I would like to add to the answer given by msqar. If you are going to use Google Fonts Webpack Plugin: (https://www.npmjs.com/package/google-fonts-webpack-plugin ) and you are using the Vue CLI, you can add a vue.config.js file inside the root of your project. See Vue CLI docs: (https://cli.vuejs.org/guide/webpack.html#simple-configuration)

Then add the code to that file:

 const GoogleFontsPlugin = require("google-fonts-webpack-plugin");

 module.exports = {
    chainWebpack: config => {
        plugins: [
            new GoogleFontsPlugin({
                fonts: [
                    { family: "Source Sans Pro" }
                ]
            })
        ]
     }
 }

Solution 4:

I didn't see a good example of using web fonts locally in Vue. So here is an example of what I used. I have some SASS variables and web fonts defined in a CSS file that gets globally added to my app so I don't have to individually import each file into my components. Note that the import for web fonts has a different syntax for the asset folder alias ~@/assets.

vue.config.js

css: {
    loaderOptions: {
      sass: {
        data: `
          @import "@/assets/css/global.scss";
        `
      }
    }
  }

In my CSS file global.scss I have:

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('OpenSans-Regular-400'), url(~@/assets/fonts/OpenSans-Regular-400.woff) format('woff');
}

/* color variables */

$corporate-blue: #005496;