• CRA(create-react-app) 환경에서 절대경로 / 전역 Sass 사용하기

    2022. 3. 16.

    by. 나나 (nykim)

    320x100

     

     

    CRA
    - 리액트 프로젝트를 뚝딱 시작할 수 있게 돕는 보일러 플레이트* (*자주 쓰는 수식, 명령어 등을 미리 입력해 놓는 것)
    - 그래서 번거롭게 Babel, ESLint, Webpack 등을 따로 설치할 필요가 없다

     

     

    CRA(create-react-app)에서 config 건드리기

     

    절대경로 설정(alias)을 하려면 Webpack의 config를 건드려야 하지만, CRA로 생성하면 기본적으로 config 파일을 볼 수 없다.

    eject 하면 숨겨져 있던 config 파일을 밖으로 꺼낼 수 있지만, 이거 한 번 하면 못 돌리는 옵션인데.... 웹팩이랑 안 친한데.... 🥺

     

    이럴 땐 CRACO(Create React App Configuration Override) 를 사용하자! eject 없이 설정을 건드릴 수 있다 🙌

     

    $ yarn add @craco/craco
    $ yarn add -D craco-sass-resources-loader

     

     

    설치한 후 config 파일들을 슥슥 만져준다.

     

     

    1. craco가 명령어를 실행하도록 바꾸기

     

    /* package.json 수정 */
    
    {
    	...
    	"scripts": {
    		"start": "craco start",
    		"build": "craco build",
    		"test": "craco test",
    	},
        ...
    }
    

     

     

    2. craco.config.js 파일 설정

    - 타입스크립트 환경이여서 plugins.options.source 를 tsconfig 로 설정했다. (자바스크립트 환경이라면 jsconfig)

     

    /* craco.config.js 생성 */
    
    const CracoAlias = require('craco-alias');
    
    module.exports = {
      plugins: [
        {
          plugin: CracoAlias,
          options: {
            source: 'tsconfig',
            tsConfigPath: 'tsconfig.paths.json'
          }
        }
      ]
    };

     

     

    3.  tsconfig.paths.json 생성 후 경로 설정

    - 별도 파일로 분리하지 않고 config.js 내에 직접 입력해도 무관!

     

    /* tsconfig.paths.json 생성 */
    
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"]
          // 또는 "@components/*": ["src/components/*"] 처럼 지정 가능
        }
      }
    }

     

     

    4. tsconfig.json 수정

    - 컴파일하는 데 필요한 루트 파일과 컴파일러 옵션을 지정하는 파일

      - extends: 다른 파일의 설정을 상속

      - include: 컴파일 할때 포함할 폴더나 파일

     

    /* tsconfig.json 수정 */
    
    {
      "extends": "./tsconfig.paths.json",
      "compilerOptions": {
        //...
      },
      "include": ["src", "tsconfig.paths.json"]
    }
    

     

     

    이렇게 하면 @/components/button 또는 @/styles/_mixin.scss 와 같이 불러와 쓸 수 있다.

    이제 craco.config.js 에서 글로벌로 적용할 스타일을 @/styles/로 지정해 줄 수 있다.

     

    const CracoAlias = require('craco-alias');
    
    module.exports = {
      style: {
        sass: {
          loaderOptions: {
            additionalData: `
              @import "@/styles/_variable.scss";
              @import "@/styles/_mixin.scss";
            `
          }
        }
      },
      plugins: [
        {
          plugin: CracoAlias,
          options: {
            source: 'tsconfig',
            tsConfigPath: 'tsconfig.paths.json'
          }
        }
      ]
    };

     

     

     

     

    덧1) CRA 기반 Storybook에서 전역 변수 이해하게 만들기

     

    와... 어마무시한 삽질!!

    이렇게만 했더니 스토리북에서는 전역 변수를 이해하지 못해서 여러 방면으로 타일러보다가 (왜 이해하질 못하니ㅠㅠ!!)

    스토리북의 main.js 에서 sass-loader 에 additionalData 넣는 걸로 해결.

     

    /* .storybook/main.js */
    
    module.exports = {
      //...
      webpackFinal: async (config, { configType }) => {
        config.module.rules.push({
          test: /\.scss$/,
          use: [
            {
              loader: 'sass-loader',
              options: {
                additionalData: `
                @import "./src/styles/_variable.scss";
                @import "./src/styles/_mixin.scss";
    		  `	
              }
            }
          ]
        });
        return config;
      }
    };

     

    이유는 모르겠으나 sass-loader 외에 style-loader 나 css-loader도 같이 지정하게 되면,

    "import API from "!../../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js";" 에러가 붐붐쳌.

    아무래도 기본 설정이랑 어딘가에서 충돌이 나는 것 같지만 지금으로선 알 수 없다... 😭

    (참고) (참고) (참고)

     

     

     

     

     

    덧2) Vite 환경에서 설정하기

     

    CRACO 없이 tsconfig.json, vite.config.js 파일을 설정해주면 된다.

    굳이 paths.json 으로 빼지 않고 tsconfig.json 에 경로를 입력해주고, vite.config.ts에 alias를 지정해 준 모습👇

     

    /* tsconfig.json */
    
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"]
        }
      }
    }
    
    /* vite.config.ts */
    
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import * as path from 'path';
    
    // <https://vitejs.dev/config/>
    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src')
        }
      },
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `
              @import '@/styles/_variable.scss';
              @import '@/styles/_mixin.scss';
            `,
          },
        },
      },
    });

     

     

     

    마무리는 역시...

     

    야..얍! Ⓒ LINE+

     

    728x90

    '🐿 > JS' 카테고리의 다른 글

    코어자바스크립트 - 자바스크립트 기본  (0) 2022.01.02
    2021년 회고  (0) 2021.12.29

    댓글 0