LoginSignup
2
0

Next 13 + scss でインポートエイリアスを設定する

Posted at

はじめに

最近Next 13とscssを用いてWebアプリを作る機会があり、SCSSにエイリアスを設定をする際詰まったのでその方法を紹介します

お悩み

variables.scss
$breakpoints: (
  'sm': 576px,
  'md': 768px,
  'lg': 992px,
  'xl': 1200px,
);

@mixin mq($size) {
  @media screen and (max-width: #{map-get($breakpoints, $size)}) {
    @content;
  }
}
sample.scss
@use '../../../../variables' as *;

variables.scss@mixinを使いたい時、相対パスを使うのが煩わしい...

環境

npx create-next-app プロジェクト名

スクリーンショット 2023-12-19 10.45.27.png

いろいろ聞かれますが、上記のように選択してください

本題

ここからインポートエイリアスについて説明していきます

まずはモジュールのインストールから〜

npm i -D sass

今回はsrc/app/styles配下にグローバルに当てたいscssファイルを追加していきます

.
├── src
│   └── app
│       ├── favicon.ico
│       ├── layout.tsx
│       ├── page.tsx
│       ├── style.module.scss
│       └── styles
│           └── variables.scss
└── tsconfig.json

エイリアスを設定するためにはtsconfig.jsonに以下のように追記してください

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"],
      "@variables": ["./src/app/styles/variables.scss"], // ここを追加
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

実際に使いたい時は以下のようにします

sample.scss
@use '@variables' as *;

.wrapper {
  @include mq('md') {
    display: flex;
    justify-content: space-around;
    text-align: center;
    align-items: center;
  }
}
2
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
2
0