12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nuxt.jsでグローバルSass変数を使いたい

Last updated at Posted at 2019-03-05

概要

Nuxt.jsでUIフレームワークを使ってるときにフレームワークの標準のカラーテーマを上書きして、上書きした値をSass変数にしてコンポーネント内で使いたい、なんてことありませんか?

今回はbootstrap-vueとbuefyを例にその方法を紹介したいと思います。

bootstrap-vue

bootstrap-vueが既にインストールされている前提で話します。
まだインストールしていない人はcreate-nuxt-appでbootstrap-vueを選ぶか、公式ドキュメントでインストール方法を調べましょう。

まずSassが使えるようにします。

npm i node-sass sass-loader

次にassets内にbootstrap-vue内の変数上書き用のSassファイルを作ります。上書きするためにここでbootstrapとbootstrap-vueのscssファイルをインポートします。

assets/style/_override.scss
$primary: red;

@import 'bootstrap/scss/bootstrap.scss';
@import 'bootstrap-vue/src/index.scss';

次にNuxt.jsを以下のように

nuxt.config.js

export default {
  css: ['@/assets/style/_override.scss'],

  modules: [
    'bootstrap-vue/nuxt',
  ],

  // _override.scssで既に読み込んでいるのでここはfalseにする
  bootstrapVue: {
    bootstrapCSS: false, // or `css`
    bootstrapVueCSS: false // or `bvCSS`
  },
}

これでbootstrap-vue内の$primaryがredになります。
variantプロップスでprimaryを選んだ場合も赤になります。

しかしこれではコンポーネント内のstyleブロックで$primaryを呼んだらエラーになります。

$primaryをグローバルにするためにもうひと工夫します。
先日書いたNuxt.jsでグローバルSass変数を使いたいんじゃを使うとうまくいきます。

とりあえず@nuxtjs/style-resourcesをインストールします。

npm
npm i @nuxtjs/style-resources

次にグローバルにしたいSass変数を記入します

assets/style/_variables.scss
$primary: red;

最終的にNuxt.config.jsが以下のようになります。

nuxt.config.js

export default {
  css: ['@/assets/style/_override.scss'],

  modules: [
    'bootstrap-vue/nuxt',
    '@nuxtjs/style-resources'
  ],

  // _override.scssで既に読み込んでいるのでここはfalseにする
  bootstrapVue: {
    bootstrapCSS: false, // or `css`
    bootstrapVueCSS: false // or `bvCSS`
  },

  styleResources: {
    scss: ['@/assets/style/_variables.scss']
  },
}
12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?