The correct method for including a CSS file in a Vue.js application

How can external CSS files be properly added in a Vue.js Application?

I have come across multiple methods for adding CSS files in a Vue.js Application.

One suggestion is to use the following code:

<link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
.

Another suggestion involves using:

<style lang="scss">
@import 'src/assets/css/mycss_lib.css';
</style>

Some recommend using this method:

require('./assets/layout3/css/layout.min.css')

Others advise adding the below code in webpack.config.js:

{
    test: /\.(css|less)$/,
    use: [{
         loader: "style-loader" // creates style nodes from JS strings
    }, {
         loader: "css-loader" // translates CSS into CommonJS
    }, {
         loader: "less-loader" // compiles Less to CSS
    }]
  }

An alternative approach suggested by some is:

<style src="../node_modules/vue-multiselect/dist/vue-multiselect.min.css"></style>

What are the advantages and disadvantages of implementing these various methods?

I am looking for a way to consolidate all CSS files into a single file during deployment, thereby improving loading times for my application.

Answer №1

  1. Set up sass
npm install sass-loader --save-dev
  1. Establish a new styles folder inside your src/assets directory

  2. Create a custom-styles.scss file in the newly created styles folder

  3. Include the following line of code into your main.js script

import '../src/assets/styles/custom-styles.scss';

In the custom-styles.scss file, you have the option to import multiple css files.

@import '~bootstrap/scss/bootstrap.min.css';
@import './common.css';

You can also add regular CSS declarations within the same file like this

body {
  background: gray;
}

div {
  font-weight: bold;
}
  1. Restart your development server
npm run serve

Answer №2

In my opinion, the most effective method in Vue.js is to integrate global page-styles in the main index.html file using a link tag. This allows for easy access to the styles from anywhere on the website and ensures they are loaded when the page is initially opened. For example, in your index.html:

<link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">

The style rules for specific components can be included directly in .vue files like this: mycomponent.vue:

<style scoped>
...
</style>

EDIT:

If you prefer working with .js files instead of .vue files, it's not possible to scope the CSS within components. In such cases, I always suggest naming the CSS file the same as the component and including it in the index.html file using a link tag.

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

In order to position an inner div in the center and have it expand equally at the top and bottom according to the content size

I am currently working on a layout that involves an inner div with a text div. My goal is to center the inner text div vertically and increase the size of the text div equally from both the top and bottom based on the content size. Below is the approach ...

Identify any fresh elements incorporated into the DOM following an AJAX call

I'm attempting to showcase a newly added div element within the DOM using AJAX. Through AJAX/PHP, I dynamically inserted some new buttons: <button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index ...

Challenge with constructing HTML structures

I created a table in HTML: <table cellpadding="0" cellspacing="0" border="0" style="width:1000px" id="maintable"> <thead> <tr> <th class="asc" width="30"><h3>ID</h3></th> <th width="200">&l ...

ng-options encounters duplicate data when using group by in Internet Explorer

The dropdown menu that lists states works fine in Google Chrome, but duplicates groups in Internet Explorer. In Chrome, there are 2 groups, but in IE there are 4. How can I fix this issue in IE as well? Thank you. Here is the code snippet: <!DOCTYPE h ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

What is the best way to transform URL images on a webpage into media library images in WordPress?

Having trouble converting HTML Static Sites to WordPress because images are hosted through HTML SRC Code. After conversion, no one can see the images in visual format on pages during editing. Is there a way to convert all image links inside pages to media ...

Tips on controlling the color of an input field in a form using React

Within my React app, there is a text input field situated inside a form that displays in its default gray color before any interaction: https://i.stack.imgur.com/FdNos.png Once the input field is clicked on, it changes to white as shown here: https://i.s ...

AngularJS has encountered an issue with a route resolve promise that has not been completely resolved

I'm currently working on a simple task to manage user roles within routes. The goal is straightforward: Verify the role of the logged-in user on each route (using a resolve function to authenticate the user based on token or login credentials) Direc ...

Troubleshoot: No flash message displaying on inertiajs with Laravel

Here is a summary of my current setup: Laravel 10, inertiajs v1 In the HandleInertiaRequests file: public function share(Request $request): array { return array_merge(parent::share($request), [ 'flash' => [ 'succ ...

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

The react-datepicker component is unable to set the state to the format dd/MM/yy

The date is currently shown in the correct format (31/08/21), but when onChange gets triggered, startDate changes to something like this: Tue Aug 31 2021 21:29:17 GMT+0200 (Central European Summer Time) Is there a way to maintain the display format I wa ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

The context of the Nuxt.js3 plugin loses its definition

Currently, I am working on a project that involves Nuxt.js3 and supabase integration. In my plugins/supabase.server.js file (I am still unsure whether using server or client is the best approach), I want to call "supabase = createClient(~~)" from index.vu ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

Inheriting the viewBox attribute with SvgIcon

I have a collection of unique custom SVGs, each with its own distinct viewBox. First Custom SVG <svg viewBox="-4 -4 24 24"><path something/></svg> Second Custom SVG <svg viewBox="-5 -7 24 24"><path something ...

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

Transmit an unmodifiable array using JSON and Ajax

Is there a way to transmit arrays in a non-editable format? The data I wish to transmit looks like this: var items = []; //console.log(JSON.stringify(items)); allitems = JSON.stringify(items); [{ "assetid": "7814010469", "classid": "1797256701", ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...