What is the process for loading a font file in Vue.js and webpack?

I've done a lot of research, but I couldn't find any links that show me exactly how to add fonts in VueJS. This is the method I'm using to import the font in my LESS file:

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

@font-face {
  font-family: "Galano_Grotesque_extra_Bold";
  src: url("../../fonts/Galano_Grotesque_Bold.otf");
}

@font-face {
  font-family: "Galano_Grotesque_Bold";
  src: url("../../fonts/Galano_Grotesque_DEMO_Bold.otf");
}

However, when trying to implement this, I encountered the following error:

ERROR in ./src/themes/jatango-theme/components/fonts/Galano_Grotesque_Bold.otf 1:4 Module parse failed: Unexpected character '' (1:4) You may need an appropriate loader to handle this file type. (Source code omitted for this binary file)

I am new to VueJS and have no prior experience with React or Angular. My knowledge is limited to jQuery and JavaScript. Can someone please provide me with a detailed guide on how to properly include these fonts? Thank you in advance :)

Answer №1

Make sure to store your fonts in the designated public/fonts/ directory. When referencing these fonts in your css or scss files, start with the path /fonts/.

For example, when using 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;
}

Remember to import your scss file into main.js like this:

Example:

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

You can also configure this 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";'
      },
    },
  },
...
}

Answer №2

If you're encountering issues with Vue.js specifically when using .otf files, try switching to .woff format instead. This simple change resolved the error for me and now everything is working smoothly. Just add the following code snippet to your webpack.config.js file:

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

Then, make sure to import the font files in your css file similar to this:

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

Answer №3

This issue is related to webpack and can be fixed by adding a proper webpack loader for handling font files. My preferred method is using the file-loader for fonts:

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

To resolve this issue, insert the above code into your webpack configuration file (within the module > rules section) or if you are using vue-cli 3, add it to your vue.config.js file (inside the configurewebpack section).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Personalized design created using v-for

I have an array being passed through v-for and I want to use the values within the "style" attribute. Essentially, I need to append the value from v-for to style:"left"+EachValue+"px", but I'm having trouble with the syntax. I'm unsure if this ap ...

retrieve data properties from an object

Suppose I have the following setup: var myObj = [ { name: 'A', number: 'b1', level: 0 }, { name: 'B', number: 'b2', level: 0 }, ]; I need to figure out how to retrieve all the names and format them like this: ...

Enabling Context Isolation in Electron.js and Next.js with Nextron: A Step-by-Step Guide

I've been working on a desktop application using Nextron (Electron.js + Next.js). Attempting to activate context isolation from BrowserWindow parameters, I have utilized the following code: contextIsolation: true However, it seems that this doesn&ap ...

Clearing input fields after entering information

Is there a way to automatically assign the value from a scanner input to a variable in an input box and clear it for the next input? HTML <ion-view hide-nav-bar="true"> <ion-content class="padding"><br> <label class="item item ...

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

A guide to extracting and storing JSON data in JavaScript variables

I have integrated the CheckPoint API into my web application and I need to store the "sid" in a variable for further use. How can I achieve this? Below is the code snippet I am using to log in: var myHeaders = new Headers(); myHeaders.append("Content-Type ...

jQuery load fails to fill select dropdown

Upon page load, my code executes a call to mysql to populate a select element with data. This process works smoothly on the initial load or when the page is refreshed. However, I am encountering an issue when attempting to update or repopulate the select e ...

Every time I refresh the page, my table is getting filled with blank rows

I created a simple example featuring a form and some PHP/JavaScript code. The JavaScript is used for form validation, while the PHP is utilized to update a MySQL table. function checkForm(){ var x = document.forms['form1']['first'] ...

What is the best way to pass a bind value in an Angular function controller?

I am new to working with AngularJS and I'm trying to pass a model bind value into a function declared in the controller. However, when I try to access that value from the controller, it returns undefined. Here is the code snippet: HTML: <div> ...

The user ID variable has not been declared

After successfully retrieving the username from a link, I am facing difficulty in getting the user id back. While displaying the username works perfectly fine, I encounter an issue with fetching the userId when trying to populate the thumbnail - it shows " ...

Is it possible to integrate Google Analytics with Next.js version 13?

Is there anyone who has successfully integrated Google Analytics with NextJS 13? I tried following the steps outlined in this thread: How to implement Google Analytics with NextJS 13?, but despite doing everything as instructed, I am not seeing any data o ...

Utilize a vanilla JavaScript object as the primary model in Ember

Can a plain JS object, such as a literal object, be used as a model in EmberJS? I've noticed that all the examples in the documentation utilize Ember.Object or a datastore. I understand that I may not have access to features like observables with pl ...

Switching sub components based on routing through navigation links after logging in

I'm having an issue with my routing setup while transitioning from the login page to the main page. Here's how my Routes are structured: App.jsx <BrowserRouter> <Routes> <Route path="/main/" element={<Main ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

The issue of dynamic select not sending the POST data

Having an issue with a form where the selected country and city are not being posted correctly. Despite different names in the form and php mailer script, both selections are coming through as the country. Here's the form: <select style="width: 6 ...

Leveraging the power of Ajax in JavaScript

For my assignment, I successfully made two separate paragraphs hide and show using jQuery. Moving forward, the next step involves integrating JavaScript Ajax code to allow the paragraphs to toggle visibility. To achieve this, I created two distinct HTML fi ...

Transform a Django/Python dictionary into a JavaScript dictionary using JSON

I need to convert a Python dictionary into a JavaScript dictionary. From what I understand, I have to first convert the Python dict into JSON format and then transform it into a JavaScript Object. view.py jsonheaderdict = json.dumps(headerdict) {{jsonhe ...

Flow the child process output as it streams

I have a unique custom command line tool implemented in Python which uses the "print" statement to display its output. To interact with this tool from Node.js, I spawn a child process and send commands to it using the child.stdin.write method. Below is an ...

Exploring the creation of a dynamic graph with d3.js

I'm new to d3 and attempting to create a graph layout. var w = 1000; var h = 500; var dataset = { nodes: [{ name: 'Alice' }, { name: 'David' ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...