react-css-modulizer
A CLI to convert classnames attributes in React into CSS Modules.
Table of Contents
Motivation
CSS Modules are neat. If you have an (old) React project using plain string className
attributes with CSS files, and you want to migrate it to CSS Modules, there was no automated way of doing it.
You may manage to do some stuff with babel-plugin-react-css-modules but it requires adding import statements if you don't have them already on each file.
With this CLI, in a single command you can do the conversion.
Supported className expressions
Currently it supports two types of className expressions :
- String Literal :
<div className='alert alert-primary'/>
- String Literal inside a JSX Expression Container
<div className={'alert alert-primary'}/>
Install
// npm
npm install -g react-css-modulizer
// yarn
yarn global add react-css-modulizer
Usage
Go into the project you want to convert to CSS Modules. Assuming all your sources are under a src/
folder, run :
react-css-modulizer --path='src'
This will :
- search among all files under
src/
- read
className
attributes in*.js
and*.jsx
files - read classes in
*.css
files - figure out which className attribute refers to which css file
- copy whole
src/
folder under amodulized/
folder - apply conversion to CSS Modules under
modulized/
, modifyingclassName
attributes and addingimport
statements for css files
Command line options
Name | Descritpion | Type | Default value |
---|---|---|---|
path | Project relative path | string | src/ |
jsxPath | React files globbing pattern | string | **/{.js,.jsx} |
stylesPath | CSS files globbing pattern | string | **/*.css |
outPath | Modulized project copy output path | string | modulized/ |
debug | Run in debug if set | string | false |
className expression output format
Currently the output form is always the same :
- Single class attribute :
input:
<div className={'alert'}/>
output:
import styles from 'css/alerts.css';
/* ... */
<div className={styles.alert}/> // it gives a simple member expression
- Multiple classes attribute :
input:
<div className={'alert alert-primary'}/>
output:
import styles from 'css/alerts.css';
/* ... */
<div className={`${styles.alert} ${styles.alertPrimary}`}/> // it uses a template litteral