1
0

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 3 years have passed since last update.

saas-resources-loaderで各scssにグローバル変数を読み込ませる

Last updated at Posted at 2021-12-07

対象者

webpack、sass-loaderを使っている人。
色んな場所のscssにグローバル変数やmixinを導入したいけどいちいちimportするのが面倒な人。
特に、vueの単一ファイルコンポーネント全部のstyleにグローバル変数を効かせたい人。

インストールされているもののバージョン

私がやったのはこのバージョンだったよ、というだけなので注意。

・webpack^5.65.0
・webpack-cli^4.9.1
・style-loader^3.3.1
・css-loader^6.5.1
・sass-loader^12.3.0
・sass-resources-loader^2.2.4
・その他vue-loaderとかts-loaderとか

太字がこの記事の本質部分。
sass-resources-loaderを使うと、sass, scssをコンパイルするときにoptions.resourcesで指定したファイルを読み込んでくれるらしい。

本家のgithubには

Supports Webpack 4

書かれていたが、webpack5でもいけたよということを報告したいがためにこの記事を書いた。

コード

webpack.config.js
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
  mode: 'development',
  devtool: 'inline-source-map',
  entry: './src/js/index.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/js'),
  publicPath: ''
  },
  module: {
    rules: [
      /*
        vueとかtsとかcssとかの情報がこの辺に入る
      */
      {
        test: /\.scss/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
          {
            loader: 'sass-resources-loader',
            options: {
              resources: [
                path.resolve(__dirname, 'src/style/global.scss')
              ]
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
  ]
};

ファイル構成

root/
  ┣ index.html
  ┣ dist/js/bundle.js
  ┣ src/
      ┠ js
          ├ index.ts
          └ その他jsとかtsとかvueとかのファイル
      ┗ style
          ├ global.scss
          └ style.scss
  ┣ webpack.config.js
  ┣ package.json
  ┣ package-lock.json
  ┗ node_modules/

備考

test: /\scss/の欄にsaas-resources-loaderのことを書いておけば.vueファイルの中のscssにも適用してくれるので、test: /\vue/のところに重ねて書く必要はない。

参考ページ

webpack/sass-loaderでimport毎に共通ファイルを読み込ませる
本当はこんな風にsaas-loaderのoptions.dataで追記させたかったけど、上手くいかなかった。

shakacode/sass-resources-loader - GitHub
本家のGitHubページ。

Vueで共通のSCSS(SASS)をwebpack(3系と4系)で読み込む方法
webpack3, 4で試しているページ。5でもいけた。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?