Skip to content
Advertisement

Proper way of adding CSS file in Vue.js Application

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement