8

What is the proper way of adding external CSS file in Vue.js Application ?

I found several ways to add CSS file in Vue.js Application.

Some one suggest to use this one. <link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">.

Some one suggest this one

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

Some one suggest this one

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

Some one suggest to use 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
    }]
  }

Some one suggest to use this one

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

What are the merits and demerits of using all those ways ?

I would like to use in a way so that all CSS files become a single file at the time of deployment. So that my application loads faster.

2 Answers 2

9
  1. Install sass
npm install sass-loader --save-dev
  1. Create new css directory under your src/assets directory

  2. Create a styles.scss file in the new css directory

  3. Add the following line of code to your main.js file

import '../src/assets/css/styles.scss';

In the styles.scss file you can import multiple css files.

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

You can also write regular CSS properties like this in the same file

body {
  background: gray;
}

div {
  font-weight: bold;
}
  1. Restart your dev server
npm run serve
Sign up to request clarification or add additional context in comments.

Comments

1

The best way for me(!) in Vue.js is to include global page-styles in my main index.html with a link tag. This way they are accessible from everywhere and are loaded when the page is first opened. Like this: index.html:

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

The style-rules for my components are inlined in .vue-files using: mycomponent.vue:

<style scoped>
...
</style>

EDIT:

If you don't want to use .vue files and work with .js files you can not scope the css inside components. If thats the case I always name them the same as the component and also include it inside index.html in link tag.

2 Comments

Thanks @informant09. I have several style sheets. Should I include them using several <link> tag ?
Yes one Link Tag for each style. Feel free to Post your changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.