Nyhetsbrev

Få artiklar, råd och tips om:

Du kan läsa mer om vår policy och vår hantering av persondata här.

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 and module tags.

<!--Normalstyles-->
<style src="./filename.scss" lang="scss">
    //Note that any other styles here are ignored
</style>
<!--Scoped styles-->
<style scoped src="./filename.scss" lang="scss">
    //Note that any other styles here are ignored
</style>
<!--CSS Module styles-->
<template>
   <p :class="$style.classname">Remember to add the classes with js.</p>
</template>

<!--Remember to add the '.module' suffix just before the file extension.-->
<style module src="./filename.module.scss" lang="scss">
    //Note that any other styles here are ignored
    //Only the styles in the src import are being used.
</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

Fler inlägg

img

Blend Modes in CSS

img

CSS Modules in Nuxt.js

img

Working with CSS in Nuxt.js