Combining vueJS and webpack to bring in fonts, CSS styles, and node_modules into your project

I've recently started working with Vue.js and Webpack, and I'm facing some challenges regarding the correct way to import and reference fonts, CSS, and node_modules in my project.

My project structure looks like this, as set up by vue-cli:

build
config
node_modules
src
--assets
--components
--router
static

Here's a snippet from my webpack.base.conf file:

var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

// More webpack configuration code goes here...

The main question I have is about the correct location to store custom CSS files and images. Currently, I'm placing them inside assets/css and assets/img directories respectively that I created. Is this the right approach?

In addition to custom styles, I also need to include CSS and fonts from external libraries such as Bootstrap and Font Awesome which are installed via npm and located in node_modules.

Webpack seems to handle these external resources, but I'm unsure of the correct way to reference them in my Vue components and CSS files. While using import statements works to some extent, I am not certain if there is a better practice for specifying the paths.

For example, within my custom CSS, I try to refer to fonts from an external library like this:

src: url('/node_modules/roboto-fontface/fonts/Roboto/Roboto-LightItalic.eot')

Although the code compiles, it results in a 404 error when loading the web page due to incorrect font references. How should these fonts be correctly referenced in the custom CSS?

Answer №1

Is it correct to place my custom css and images inside assets/css and assets/img folders that I created?

The answer is yes, although it's somewhat subjective. The CLI tool has already set up these folders for you and configured certain things in the Webpack config files, so it makes sense to utilize them.

Using import './assets/css/style.css'import '../node_modules/path/to/bootstrap.min.css' seems to work fine in production, but is there a better way to specify the paths?

Webpack actually embeds CSS into its JS file, so importing it is necessary for Webpack to recognize it. Here's an example of dynamically loading images:

    <ul id="albums">
    <li v-for="album in albums">
        <img :src="LoadImage(album.data.imagefile)" />
    </li>
</ul>

To ensure proper image loading, use a method like this:

LoadImage(filename) {
        const image = require('@/assets/img/' + filename)
        return image
    }

By using imports/require functions, Webpack is able to process your files correctly.

In my custom css files, I reference external fonts with urls like: src: url('/node_modules/roboto-fontface/fonts/Roboto/Roboto-LightItalic.eot'). However, I get a 404 Error when trying to load these fonts. How should I adjust the font references?

It's advisable to copy all required files to your src folder instead of relying on dist. In terms of referencing fonts, consider how browsers interpret url paths. You may need to adjust the references to be relative paths within your project structure.

If you found this information helpful or have further questions, feel free to visit to engage with the Vue.js community and core team members.

Answer №2

Simple fix To solve the problem, I decided to disable the @font-face {} section and then included my own custom CSS in the style file.

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

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

Learn how to dynamically clear and update source data in jQuery autocomplete for enhanced functionality

Here is a snippet of my jQuery code. In this code, 'year' refers to the form input tag ID, and 'years' is an array variable containing all the year values. I have set this array as the source for autocomplete, which works fine. However, ...

jquery hover effect not functioning properly

I have a question regarding my jquery mobile application. I am trying to implement a hover effect on items with the class grid-item, where the width and height change simultaneously in an animation. Here is the code snippet I am using: $('.grid-i ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Incorporate an Angular app into an existing application and seamlessly transfer the data

I am currently in the process of integrating an Angular app into an existing jQuery application. Let's say I have a basic button in my HTML code. My goal is to load the Angular app and execute controller code when the button is clicked. To achieve t ...

Utilizing Typeface Styles in SCSS with the Latest Webpack Version 4

My Angular 6 SPA utilizes Webpack 4 for bundling, and I have encountered an issue while trying to import external fonts into the project. The project is based on the repository found at; AngularWebpackVisualStudio Example Repo After inspecting the webpac ...

Dealing with the issue of receiving raw JavaScript in the .ajax error function even when receiving a 200

I am encountering an issue with a jQuery.ajax() call to a third-party product. The POST request is successful, returning a 200 OK status code, but instead of executing the success function, it redirects to the error function. The response variable displays ...

The vanishing act: Semantic UI menu disappears when you click

My objective is to create a persistent left-side menu using Semantic-UI. I want to implement two different states for the menu - one with text for each item and another with an image for each item. However, I am facing some challenges that have me complete ...

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

"Adding a class with jQuery on a selected tab and removing it when another tab is clicked

I have 3 different tabs named Monthly, Bi-monthly, and Weekly. The user can set one of these as their default payroll period, causing that tab to become active. I was able to achieve this functionality by utilizing the following code within the <script& ...

Can you explain the significance of the res.render callback parameter in Express 4.0 for Node.js?

Can you explain the role of the res.render callback argument? When would it be necessary to use this callback argument, especially when there is already a template specified as the first argument? The following code snippet is taken from the official doc ...

Encountering an issue with file uploading in Firebase: Error message indicates that AppCheck is being utilized before activation

I am facing an issue while trying to upload a file to my firebase account. Whenever I attempt this, I encounter the following error message: Uncaught (in promise) FirebaseError: AppCheck: AppCheck is being used before activate() is called for FirebaseApp ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...

Learn the secrets of displaying a pop-up alert message seamlessly without interrupting the page's rendering process. Additionally, discover how to effortlessly refresh a chart every

I need to display a pop-up if the value is less than 3. I have tried using the alert function, but it causes the page to not render. How can I show the pop-up without blocking the page and refresh the chart every 30 seconds? <script> ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Is it possible to conduct Vue unit tests without incorporating a component, solely relying on the Vue Instance?

After a quick glance at the information provided on Vue Unit Testing This is what I found: It was mentioned that anything compatible with a module-based build system will work The documentation highlights methods for testing components In my specific ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Using JavaScript to extract data from a JSON-formatted URL

I am currently facing a challenge with parsing JSON data from a specific URL. Despite my efforts, I am unable to retrieve any information related to the "ask" and "bid" values from this JSON feed. The URL in question is . The structure of the JSON data is ...