Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
abu abu Avatar asked Jun 19 '18 10:06

abu abu


People also ask

Where do I put CSS in Vue app?

css in the src/assets directory. Files in this folder get processed by Webpack. This means we can use CSS pre-processors (like SCSS) or post-processors (like PostCSS).

How do I add external CSS to Vue?

Include CSS file in one component If you want to include the external CSS file in only one component you can import it in the <style></style> tag. For example, we want to include Bootstrap 4 CSS file in a single component. It will only work for that component.

What is the best way to add CSS?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.

How do you add a SCSS file to Vue?

You have SCSS variables in one file that you want to make available to your Vue components. The good news is that the Vue CLI makes it incredibly easy to support writing SCSS, and with Vue's single file components you can simply add lang="scss" to the <style> block ( docs).


1 Answers

  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
like image 184
Hardik Raval Avatar answered Sep 23 '22 05:09

Hardik Raval