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

Transferring information from the router to the server file using Node.js and Express

I am in the process of creating a web application using node.js, and I need to transfer data from my router file, which handles form processing, to my server file responsible for emitting events to other connected users. router.js module.exports=function ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Encasing the window global variable within an AngularJS framework

Currently, I am encapsulating a global variable within a factory in order to make it injectable. Here is an example of how it's done: angular.module('Analytics').factory('woopra', [ '$window', function ($window) ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Having issues with running multiple Vue forms with VeeValidate simultaneously on a single page

I am having trouble using VeeValidate validation on multiple forms within a Vue component. I have attempted to limit the validation to specific scopes, but it does not seem to be recognizing them correctly. The validation works fine on the first form (regi ...

Maintain consistent theme across various pages using javascript

So I successfully implemented a dark mode on the front page using the following script (sourced from W3schools) : <script> function darklightmode() { var element = document.body; element.classList.toggle("dmode"); } </script> ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

What are your thoughts on the size of a React component being 500 lines long?

Currently, I am in the process of constructing a Table component that includes filters and requires an extensive amount of logic. Additionally, I have incorporated material UI which tends to add multiple lines of code. Despite these elements, I feel that ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Is there a way to automatically fill in a MUI textfield in a React Hook form with data retrieved from Firestore?

Utilizing React Hook Forms alongside MUI TextField components has been a productive challenge for me. I've been able to successfully fetch data from Firestore and aim to prefill the form with this retrieved information. Although I am employing useFor ...

TypeScript does not raise errors for ANY variables that are initialized later

In my code, there is a function that accepts only numeric variables. function add(n1: number) { return n1 + n1; } However, I mistakenly initialized a variable with type "any" and assigned it a string value of '5'. let number1; number1 = &apo ...

Passing variables through a promise chain and utilizing the finally method

My current endeavor involves constructing a log for an Express API, yet I am encountering difficulties in extracting the data for logging. I have successfully logged the initial req and res objects within the finally block, but I am uncertain about how to ...

Incorporate JavaScript files into your Gruntfile

I utilized a bootstrap-compass project by using the yeoman generator provided in this link: https://www.npmjs.com/package/generator-bootstrap-compass You can view the file structure through the link mentioned above. Now, I am looking for guidance on cor ...

Removing duplicate entries in child components fields using Vue JS

I am facing an issue with a child component that retrieves repeating data from an Axios request. List of Colors: blue, blue, red, orange, green, green, blue Child Component <div v-if="color"> <strong> Color:</str ...

The most effective way to transmit data from an asynchronous call in Node.js while ensuring a reliable fallback routing structure

I have a request function that makes a call to an endpoint and retrieves data from it. When passing this data to an hbs template for rendering, the array is empty due to asynchronicity. Can someone guide me on the correct approach? Below is the code snippe ...

Jest spyOn is detecting that a function was invoked with an unexpected object instead of the intended one

When using Jest's spyOn to monitor a method on Vue router, the method being tested in Vue code may look something like this: myMethod() { this.$router.push({ name: "login" }); } The goal is to confirm that $router.push was called during testing, s ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

Generate three random names from an array and assign them to an element

This website is amazing! I've interacted with so many awesome people here! Currently, I have successfully implemented code to get one random name from an array. However, I now want to display three different names each time, and I'm facing a roa ...

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...