nuxt-modules / style-resources

Style Resources for Nuxt 3
MIT License
589 stars 22 forks source link
import less nuxt nuxt-module nuxtjs sass stylus

Style Resources for Nuxt 3 - Nobody likes extra @import statements!

npm version npm downloads Codecov License

Nuxt 2 is supported with @nuxtjs/style-resources@^1, documentation is on v1 branch.

If you are using Vite, this module is not needed.

You can use the css.preprocessorOptions instead.

📖 Release Notes

Features

Warning

Do not import actual styles. Use this module only to import variables, mixins, functions (et cetera) as they won't exist in the actual build. Importing actual styles will include them in every component and will also make your build/HMR magnitudes slower. Do not do this!

Setup

export default defineNuxtConfig({
  modules: [
    '@nuxtjs/style-resources',
  ],

  styleResources: {
   // your settings here
   sass: [],
   scss: [],
   less: [],
   stylus: [],
   hoistUseStatements: true  // Hoists the "@use" imports. Applies only to "sass", "scss" and "less". Default: false.
  }
})

Examples

LESS Example

nuxt.config.ts:

export default defineNuxtConfig({
  css: ['~assets/global.less'],
  modules: ['@nuxtjs/style-resources'],
  styleResources: {
    less: './assets/vars/*.less'
  }
})

assets/global.less

h1 {
  color: @green;
}

assets/vars/variables.less

@gray: #333;

assets/vars/more_variables.less

@green: #00ff00;

pages/index.vue

<template>
  <div>
    <!-- This h1 will be green -->
    <h1>Test</h1>
    <test/>
  </div>
</template>

<script>
import Test from '~/components/Test'

export default {
  components: { Test }
}
</script>

components/Test.vue

<template>
  <div class="ymca">
    Test
  </div>
</template>

<style lang="less">
  .ymca {
    color: @gray; // will be resolved to #333
  }
</style>

SCSS Example

nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['@nuxtjs/style-resources'],
  styleResources: {
    scss: [
      './assets/vars/*.scss',
      './assets/abstracts/_mixins.scss' // use underscore "_" & also file extension ".scss"
      ]
  }
})

Instead of './assets/abstracts/_mixins.scss' you can use also '~assets/abstracts/_mixins.scss'

assets/vars/_colors.scss

$gray: #333;

assets/abstracts/_mixins.scss

@mixin center() {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
}

components/Test.vue

<template>
  <div class="ymca">
    Test
  </div>
</template>

<style lang="scss">
  .ymca {
    @include center; // will be resolved as position:absolute....
    color: $gray; // will be resolved to #333
  }
</style>

License

Inspired by nuxt-sass-resources-loader.

MIT License

Copyright (c) Alexander Lichter