Subscribe to our Newsletter

Get articles, advice and tips about:

You can read more about our privacy policy and how we use your personal data here.

CSS in Nuxt.js

Importing Styles to Component Style Tags in Nuxt.js

by Frida Nyvall

Third article in a series about working with CSS in Nuxt.js, examining how to import styles to component style tags in Nuxt.

In Vue.js projects, there are different ways of importing styles to a project. See the article “Importing Style Files to Component Style Tags in Vue.js” for more info.

In Nuxt.js projects, there are similar ways of importing styles, however with some slight differences.

Importing Global Styles in Component Style Tags

Importing global styles to be used in component style tags. A convenient way of not having to import certain files manually every time for every component. This is meant for adding the type of SCSS files that contains mixins and variables that will not generate any output before they are being used in a context. This is because it will be added to each component’s CSS when imported.

Making this type of import has been made available natively in Vue.js, but Nuxt.js still seems to be in need of a plugin. In the project folder, run:

npm install --save-dev @nuxtjs/style-resources

Add the following to your nuxt.config file:

/*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/style-resources'
  ],

  /*@nuxtjs/style-resources*/
  styleResources: {
    //array of strings that are paths to the file:
    scss: ['~assets/styles/globalvariables.scss']
  },

:src Imports

Importing separate style files in the style tag by using “src” imports seems to work the same for Nuxt.js as in Vue.js.

For example pages/subfolder/filename.scss can be used with for example pages/subfolder/index.vue. This works for normal as well as scoped style tags, but I was not able to get it to work with the module keyword.

<style src="./filename.scss" lang="scss">
    //Note that any other styles here are ignored
</style>
<style scoped src="./filename.scss" lang="scss">
    //Note that any other styles here are ignored
</style>

To read more about src imports, see the section “:src Imports” in the article “Importing Style Files to Component Style Tags in Vue.js”.

Articles in this series

Tags

More posts

img

CSS Modules in Nuxt.js

img

Working with CSS in Nuxt.js

img

CSS Modules in Vue.js