【Vue.js】Vue-CLI(4.1.1)でSCSSを読み込む手順


はじめに

Vue-CLIを使ってSCSSファイルを読み込むための記事は数多くヒットするのですが、古い情報も多いです。

そのため、自分がVue-CLI 4.1.1でうまくいった手順を残しておきます。

この記事が役に立つ方

  • Vue-CLI4.1.1でSCSSを読み込みたい方

この記事のメリット

  • 無事SCSSが読み込めるようになる

環境

OS: macOS Catalina 10.15.1
zsh: 5.7.1
Vue: 2.6.10
vue-cli: 4.1.1

手順

1.新規プロジェクト作成

まずはVue-CLIで新しく生成します。

今回プロジェクト名はtestとします。

※長ったらしくなりますが、一応全て載せておきます。

$ vue create test
Vue CLI v4.1.1
? Please pick a preset: 
  MyStandard (node-sass, babel, router, vuex, eslint) 
  default (babel, eslint) 
❯ Manually select features 
? Check the features needed for your project: 
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
❯◉ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) (Y/n) y
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): 
  Sass/SCSS (with dart-sass) 
❯ Sass/SCSS (with node-sass) 
  Less 
  Stylus 
? Pick a linter / formatter config: (Use arrow keys)
❯ ESLint with error prevention only 
  ESLint + Airbnb config 
  ESLint + Standard config 
  ESLint + Prettier 
? Where do you prefer placing config for Babel, ESLint, etc.? 
❯ In dedicated config files 
  In package.json 
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to inver
t selection)
❯◉ Lint on save
 ◯ Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? 
❯ In dedicated config files 
  In package.json 

最後の設定保存はお好みで良いと思います。


2.SCSSファイルの用意

ここからはこの記事の通りに実施でOKでした。(助かりました!)
Vue CLI 3でグローバルなSCSSを読み込ませる - Qiita

SCSSの構成は、今回説明用なのでかなりシンプルにしておきます。

メイン

test/src/assets/sass/main.scss

変数定義・mixinなど直接スタイル定義しないもの

test/src/assets/sass/prepends.scss


3.main.jsに追記

main.js
require('@/assets/sass/main.scss')

main.scssを読み込みます。


4.vue.config.jsを作成

touch vue.config.js

testディレクトリ直下に移動し、vue.config.jsを作成します。

package.jsonがあるディレクトリです。


5.vue.config.jsに追記

vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      scss: {
        prependData: '@import "./src/assets/sass/prepends.scss";'
      }
    }
  }
};

こちらにprepends.scssを読み込みます。


6.yarn serve

yarn serve

vue.config.jsに追記した後はビルドし直す必要があります。

以上です!
これで無事にSCSSが読み込める状態になっているはずです

おわりに

最後まで読んで頂きありがとうございました

どなたかの役に立てれば幸いです

参考にさせて頂いたサイト(いつもありがとうございます)

Vue CLI 3でグローバルなSCSSを読み込ませる - Qiita