-
Typescript 기반의 React에서 css module 사용 설정설치&설정 관련 2021. 6. 23. 22:50728x90
React 기반의 Storybook에서 css module 사용 설정
기간계 디자인 시스템을 진행하면서 storybook 을 이용하고 있습니다.
이번에 css module을 사용하기 위해서 몇가지 설정을 했는데, 검색에 많은 시간이 걸렸습니다.들어가기에 앞서서
크게 storybook 설정과 typescript + rollup 설정으로 나뉩니다.
typescript + rollup의 경우 배포와 관련이 있습니다.storybook 설정하기
sotrybook설정은 Add loader for .module.css to load CSS modules 내용을 참고하면 쉽게 됩니다.
// ./storybook/main.js module.exports = { stories: ['../stories/**/*.stories.js'], addons: ['@storybook/addon-actions', '@storybook/addon-links'], webpackFinal: async (config, { configType }) => { // get index of css rule const ruleCssIndex = config.module.rules.findIndex(rule => rule.test.toString() === '/\\.css$/'); // map over the 'use' array of the css rule and set the 'module' option to true config.module.rules[ruleCssIndex].use.map(item => { if (item.loader && item.loader.includes('/css-loader/')) { item.options.modules = { mode: 'local', localIdentName: configType === 'PRODUCTION' ? '[local]--[hash:base64:5]' : '[name]__[local]--[hash:base64:5]', }; } return item; }) // Return the altered config return config; } };
typescript + rollup 설정
먼저 typescript 설정을 위해서 typescript-plugin-css-modules 모듈을 사용하여야 합니다.
# 설치 yarn add -D typescript-plugin-css-modules
tsconfig.json
파일에 아래 설정을 추가 합니다.{ "compilerOptions": { "plugins": [{ "name": "typescript-plugin-css-modules" }] } }
이것으로 typescript 설정이 완료 되었습니다.
그리고 rollup 설정은 Bundle Libraries With SCSS and CSS Modules Using Rollup 를 따라서 설정하면 쉽게 됩니다.
제 경우는
postcss
의 옵션만 추가 해서 설정을 완료 하였습니다.// rollup.config.js import babel from 'rollup-plugin-babel'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import postcss from 'rollup-plugin-postcss'; import peerDepsExternal from 'rollup-plugin-peer-deps-external'; export default { input: './src/index.js', output: [ { name: 'comlib', sourcemap: true, file: './dist/index.js', format: 'umd', globals: { react: 'React' }, }, ], plugins: [ peerDepsExternal(), postcss({ // 옵션 추가 처리 extract: false, modules: true, use: ['sass'], }), babel({ exclude: 'node_modules/**' }), resolve(), commonjs(), ], external: ['react', 'react-dom'], };
이후 배포를 하면 css module도 함께 처리가 된 것을 확인 할 수 있습니다.
css module이 적용된 예제
위의 그림과 같이
GuiButton-module_formWrap__2zPLQ
가 적용된 것을 확인 할 수 있습니다.마치며
정리해놓은 자료가 다른 누군가에게 도움이 되기를 바랍니다.
저와 같이 하루종일 고생하지 않으시길...참고자료
728x90'설치&설정 관련' 카테고리의 다른 글
WSL2를 사용하면서 host에서 특정 port 연결 (0) 2021.12.15 logstash 사용 후기 (0) 2021.07.05 wsl2를 이용시 localhost:port로 접근 오류 (0) 2020.12.28 TIP] Nginx location 설정 옵션 정보 (0) 2020.12.24 [Dockerfile] node:Alpine에서 puppeteer 기동 & 한글 깨짐 처리 (0) 2020.07.10