LoginSignup
35
31

More than 3 years have passed since last update.

Nuxt.jsで共通scssを使えるようにする

Posted at

gulp4を使ってpugやscssをコンパイルさせていたので、Nuxt.jsでも似たようなことがやりたいと思い調べました。

Nuxt.jsの環境を作る

ターミナル上で作りたいフォルダに移動し

$ npx create-nuxt-app 名前

をします。

すると色々聞かれますがこの辺は作りたいものに合わせていれてください。

cd 名前
npm run build
npm start

が出てくるのでこの通りにします。
http://localhost:3000/ でちゃんと動いていればNuxt.jsの環境は完成。

 scssを使える環境を作る

ctrl + Cで一旦止めて、今度は必要なものをインストールしていきます。

$ npm install --save-dev node-sass
$ npm install --save-dev sass-loader
$ npm install --save-dev @nuxtjs/style-resources

設定をする

nuxt.config.jsを開いて、一番下あたりに

nuxt.config.js
module.exports = {
  modules: ['@nuxtjs/style-resources'],
  styleResources: {
   scss: [
    '~/assets/scss/_index.scss'
    ]
  }
}

を記入します。読み込ませたい好きなscssで良いです。

assetsフォルダにscssフォルダを作り、そこに_index.scssファイルを作り、適当にscssを書き込みます。

assets/scss/_index.scss
$red: pink;
$background: #FFE200;

body {
  background: white;
  h1 {
    border: 1px solid red;
  }
}
$ npm run dev

↑して_index.scssの中身を書き換えると
http://localhost:3000/ にリアルタイムでページを更新してくれます。
これだけで共通のscssは完成です。

メモ

nuxt.config.js
import pkg from './package'

export default {
  mode: 'spa',

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },

  /*
  ** Global CSS
  */
  css: [
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc:https://github.com/nuxt-community/modules/tree/master/packages/bulma
    '@nuxtjs/bulma',
  ],

  /*
  ** Build configuration
  */
  build: {
    postcss: {
      preset: {
        features: {
          customProperties: false
        }
      }
    },
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    }
  }
}

module.exports = {
  modules: ['@nuxtjs/style-resources'],
  styleResources: {
   scss: [
    '~/assets/scss/_index.scss'
    ]
  }
}

package.json
{
  "name": "名前",
  "version": "1.0.0",
  "description": "説明",
  "author": "作者名",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "cross-env": "^5.2.0",
    "nuxt": "^2.4.0",
    "@nuxtjs/bulma": "^1.2.1"
  },
  "devDependencies": {
    "@nuxtjs/style-resources": "^0.1.2",
    "node-sass": "^4.12.0",
    "nodemon": "^1.18.9",
    "sass-loader": "^7.1.0"
  }
}

35
31
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
35
31