4
5

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 1 year has passed since last update.

Viteですべてのscssファイルに共通の変数を読み込ませる

Posted at

結論

vite.config.tscss.preprocessorOptions.scss.additionalDataにお好みのscssファイルを指定してあげれば、すべてのscssで指定したscssのコードを読み込んでくれる。

詳細

環境

"sass": "^1.52.3",
"sass-loader": "10",
"typescript": "^4.6.4",
"vite": "^2.9.9",
"@vitejs/plugin-react": "^1.3.0",

React + ts , CSS Modules, scss で書いていく。

具体的なコード

vite.config.tsは次のようになっている。

vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import * as path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  css: {
    modules: {
      scopeBehaviour: 'local',
    },
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/assets/scss/index.scss";`,
      },
    },
  },
  resolve: {
    alias: {
      '@/': path.join(__dirname, './src/'),
    },
  },
})

src/assets/scss/index.scssが次のようになっているとする。

src/assets/scss/index.scss
$main-color: #e98a1d;

このとき、例えばコンポーネントのスタイリングを記述する際に次のように書けば$main-colorを正しく読み込むことができている。

sec/components/Button/Button.modules.scss
.button {
  background-color: $main-color;
}
4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?