UNPKG

18.6 kBMarkdownView Raw
1# babel-plugin-react-css-modules
2
3[![Travis build status](http://img.shields.io/travis/gajus/babel-plugin-react-css-modules/master.svg?style=flat-square)](https://travis-ci.org/gajus/babel-plugin-react-css-modules)
4[![NPM version](http://img.shields.io/npm/v/babel-plugin-react-css-modules.svg?style=flat-square)](https://www.npmjs.org/package/babel-plugin-react-css-modules)
5[![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical)
6[![Gitter](https://img.shields.io/gitter/room/babel-plugin-react-css-modules/Lobby.svg?style=flat-square)](https://gitter.im/babel-plugin-react-css-modules/Lobby)
7[![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas)
8
9<img src='./.README/babel-plugin-react-css-modules.png' height='150' />
10
11Transforms `styleName` to `className` using compile time [CSS module](#css-modules) resolution.
12
13In contrast to [`react-css-modules`](https://github.com/gajus/react-css-modules), `babel-plugin-react-css-modules` has a lot smaller performance overhead (0-10% vs +50%; see [Performance](#performance)) and a lot smaller size footprint (less than 2kb vs 17kb react-css-modules + lodash dependency).
14
15* [CSS Modules](#css-modules)
16* [Difference from `react-css-modules`](#difference-from-react-css-modules)
17* [Performance](#performance)
18* [How does it work?](#how-does-it-work)
19* [Conventions](#conventions)
20 * [Anonymous reference](#anonymous-reference)
21 * [Named reference](#named-reference)
22* [Configuration](#configuration)
23 * [Configurate syntax loaders](#configurate-syntax-loaders)
24 * [Custom Attribute Mapping](#custom-attribute-mapping)
25* [Installation](#installation)
26 * [React Native](#react-native)
27 * [Demo](#demo)
28* [Example transpilations](#example-transpilations)
29 * [Anonymous `styleName` resolution](#anonymous-stylename-resolution)
30 * [Named `styleName` resolution](#named-stylename-resolution)
31 * [Runtime `styleName` resolution](#runtime-stylename-resolution)
32* [Limitations](#limitations)
33* [Have a question or want to suggest an improvement?](#have-a-question-or-want-to-suggest-an-improvement)
34* [FAQ](#faq)
35 * [How to migrate from react-css-modules to babel-plugin-react-css-modules?](#how-to-migrate-from-react-css-modules-to-babel-plugin-react-css-modules)
36 * [How to reference multiple CSS modules?](#how-to-reference-multiple-css-modules)
37 * [How to live reload the CSS?](#hot-to-live-reload-the-css)
38
39## CSS Modules
40
41[CSS Modules](https://github.com/css-modules/css-modules) are awesome! If you are not familiar with CSS Modules, it is a concept of using a module bundler such as [webpack](http://webpack.github.io/docs/) to load CSS scoped to a particular document. CSS module loader will generate a unique name for each CSS class at the time of loading the CSS document ([Interoperable CSS](https://github.com/css-modules/icss) to be precise). To see CSS Modules in practice, [webpack-demo](https://css-modules.github.io/webpack-demo/).
42
43In the context of React, CSS Modules look like this:
44
45```js
46import React from 'react';
47import styles from './table.css';
48
49export default class Table extends React.Component {
50 render () {
51 return <div className={styles.table}>
52 <div className={styles.row}>
53 <div className={styles.cell}>A0</div>
54 <div className={styles.cell}>B0</div>
55 </div>
56 </div>;
57 }
58}
59
60```
61
62Rendering the component will produce a markup similar to:
63
64```js
65<div class="table__table___32osj">
66 <div class="table__row___2w27N">
67 <div class="table__cell___1oVw5">A0</div>
68 <div class="table__cell___1oVw5">B0</div>
69 </div>
70</div>
71
72```
73
74and a corresponding CSS file that matches those CSS classes.
75
76Awesome!
77
78However, there are several several disadvantages of using CSS modules this way:
79
80* You have to use `camelCase` CSS class names.
81* You have to use `styles` object whenever constructing a `className`.
82* Mixing CSS Modules and global CSS classes is cumbersome.
83* Reference to an undefined CSS Module resolves to `undefined` without a warning.
84
85`babel-plugin-react-css-modules` automates loading of CSS Modules using `styleName` property, e.g.
86
87```js
88import React from 'react';
89import './table.css';
90
91export default class Table extends React.Component {
92 render () {
93 return <div styleName='table'>
94 <div styleName='row'>
95 <div styleName='cell'>A0</div>
96 <div styleName='cell'>B0</div>
97 </div>
98 </div>;
99 }
100}
101
102```
103
104Using `babel-plugin-react-css-modules`:
105
106* You are not forced to use the `camelCase` naming convention.
107* You do not need to refer to the `styles` object every time you use a CSS Module.
108* There is clear distinction between global CSS and CSS modules, e.g.
109
110 ```js
111 <div className='global-css' styleName='local-module'></div>
112 ```
113
114<!--
115* You are warned when `styleName` refers to an undefined CSS Module ([`errorWhenNotFound`](#errorwhennotfound) option).
116* You can enforce use of a single CSS module per `ReactElement` ([`allowMultiple`](#allowmultiple) option).
117-->
118
119## Difference from `react-css-modules`
120
121[`react-css-modules`](https://github.com/gajus/react-css-modules) introduced a convention of using `styleName` attribute to reference [CSS module](https://github.com/css-modules/css-modules). `react-css-modules` is a higher-order [React](https://facebook.github.io/react/) component. It is using the `styleName` value to construct the `className` value at the run-time. This abstraction frees a developer from needing to reference the imported styles object when using CSS modules ([What's the problem?](https://github.com/gajus/react-css-modules#whats-the-problem)). However, this approach has a measurable performance penalty (see [Performance](#performance)).
122
123`babel-plugin-react-css-modules` solves the developer experience problem without impacting the performance.
124
125## Performance
126
127The important metric here is the "Difference from the base benchmark". "base" is defined as using React with hardcoded `className` values. The lesser the difference, the bigger the performance impact.
128
129> Note:
130> This benchmark suite does not include a scenario when `babel-plugin-react-css-modules` can statically construct a literal value at the build time.
131> If a literal value of the `className` is constructed at the compile time, the performance is equal to the base benchmark.
132
133|Name|Operations per second (relative margin of error)|Sample size|Difference from the base benchmark|
134|---|---|---|---|
135|Using `className` (base)|9551 (±1.47%)|587|-0%|
136|`react-css-modules`|5914 (±2.01%)|363|-61%|
137|`babel-plugin-react-css-modules` (runtime, anonymous)|9145 (±1.94%)|540|-4%|
138|`babel-plugin-react-css-modules` (runtime, named)|8786 (±1.59%)|527|-8%|
139
140> Platform info:
141>
142> * Darwin 16.1.0 x64
143> * Node.JS 7.1.0
144> * V8 5.4.500.36
145> * NODE_ENV=production
146> * Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz × 8
147
148View the [./benchmark](./benchmark).
149
150Run the benchmark:
151
152```bash
153git clone git@github.com:gajus/babel-plugin-react-css-modules.git
154cd ./babel-plugin-react-css-modules
155npm install
156npm run build
157cd ./benchmark
158npm install
159NODE_ENV=production ./test
160```
161
162## How does it work?
163
1641. Builds index of all stylesheet imports per file (imports of files with `.css` or `.scss` extension).
1651. Uses [postcss](https://github.com/postcss/postcss) to parse the matching CSS files.
1661. Iterates through all [JSX](https://facebook.github.io/react/docs/jsx-in-depth.html) element declarations.
1671. Parses the `styleName` attribute value into anonymous and named CSS module references.
1681. Finds the CSS class name matching the CSS module reference:
169 * If `styleName` value is a string literal, generates a string literal value.
170 * If `styleName` value is a [`jSXExpressionContainer`](https://github.com/babel/babel/tree/master/packages/babel-types#jsxexpressioncontainer), uses a helper function ([`getClassName`](./src/getClassName.js)) to construct the `className` value at the runtime.
1711. Removes the `styleName` attribute from the element.
1721. Appends the resulting `className` to the existing `className` value (creates `className` attribute if one does not exist).
173
174## Configuration
175
176Configure the options for the plugin within your `.babelrc` as follows:
177
178```json
179{
180 "plugins": [
181 ["react-css-modules", {
182 "option": "value"
183 }]
184 ]
185}
186
187```
188
189### Options
190
191|Name|Type|Description|Default|
192|---|---|---|---|
193|`context`|`string`|Must match webpack [`context`](https://webpack.github.io/docs/configuration.html#context) configuration. [`css-loader`](https://github.com/webpack/css-loader) inherits `context` values from webpack. Other CSS module implementations might use different context resolution logic.|`process.cwd()`|
194|`exclude`|`string`|A RegExp that will exclude otherwise included files e.g., to exclude all styles from node_modules `exclude: 'node_modules'`|
195|`filetypes`|`?FiletypesConfigurationType`|Configure [postcss syntax loaders](https://github.com/postcss/postcss#syntaxes) like sugerss, LESS and SCSS and extra plugins for them. ||
196|`generateScopedName`|`?GenerateScopedNameConfigurationType`|Refer to [Generating scoped names](https://github.com/css-modules/postcss-modules#generating-scoped-names). If you use this option, make sure it matches the value of `localIdentName` in webpack config. See this [issue](https://github.com/gajus/babel-plugin-react-css-modules/issues/108#issuecomment-334351241) |`[path]___[name]__[local]___[hash:base64:5]`|
197|`removeImport`|`boolean`|Remove the matching style import. This option is used to enable server-side rendering.|`false`|
198|`webpackHotModuleReloading`|`boolean`|Enables hot reloading of CSS in webpack|`false`|
199|`handleMissingStyleName`|`"throw"`, `"warn"`, `"ignore"`|Determines what should be done for undefined CSS modules (using a `styleName` for which there is no CSS module defined). Setting this option to `"ignore"` is equivalent to setting `errorWhenNotFound: false` in [react-css-modules](https://github.com/gajus/react-css-modules#errorwhennotfound). |`"throw"`|
200|`attributeNames`|`?AttributeNameMapType`|Refer to [Custom Attribute Mapping](#custom-attribute-mapping)|`{"styleName": "className"}`|
201
202Missing a configuration? [Raise an issue](https://github.com/gajus/babel-plugin-react-css-modules/issues/new?title=New%20configuration:).
203
204> Note:
205> The default configuration should work out of the box with the [css-loader](https://github.com/webpack/css-loader).
206
207#### Option types (flow)
208
209```js
210type FiletypeOptionsType = {|
211 +syntax: string,
212 +plugins?: $ReadOnlyArray<string | $ReadOnlyArray<[string, mixed]>>
213|};
214
215type FiletypesConfigurationType = {
216 [key: string]: FiletypeOptionsType
217};
218
219type GenerateScopedNameType = (localName: string, resourcePath: string) => string;
220
221type GenerateScopedNameConfigurationType = GenerateScopedNameType | string;
222
223type AttributeNameMapType = {
224 [key: string]: string
225};
226
227```
228
229### Configurate syntax loaders
230
231To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:
232
2331. Add the [postcss syntax loader](https://github.com/postcss/postcss#syntaxes) as a development dependency:
234
235 ```bash
236 npm install postcss-scss --save-dev
237 ```
238
2392. Add a filetype syntax mapping to the Babel plugin configuration
240
241 ```json
242 "filetypes": {
243 ".scss": {
244 "syntax": "postcss-scss"
245 }
246 }
247 ```
248
249 And optionaly specify extra plugins
250
251 ```json
252 "filetypes": {
253 ".scss": {
254 "syntax": "postcss-scss",
255 "plugins": [
256 "postcss-nested"
257 ]
258 }
259 }
260 ```
261
262 Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config
263
264 ```json
265 "plugins": [
266 ["postcss-import-sync2", {
267 "path": ["src/styles", "shared/styles"]
268 }],
269 "postcss-nested"
270 ]
271 ```
272
273
274### Custom Attribute Mapping
275
276You can set your own attribute mapping rules using the `attributeNames` option.
277
278It's an object, where keys are source attribute names and values are destination attribute names.
279
280For example, the [&lt;NavLink&gt;](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md) component from [React Router](https://github.com/ReactTraining/react-router) has a `activeClassName` attribute to accept an additional class name. You can set `"attributeNames": { "activeStyleName": "activeClassName" }` to transform it.
281
282The default `styleName` -> `className` transformation **will not** be affected by an `attributeNames` value without a `styleName` key. Of course you can use `{ "styleName": "somethingOther" }` to change it, or use `{ "styleName": null }` to disable it.
283
284## Installation
285
286When `babel-plugin-react-css-modules` cannot resolve CSS module at a compile time, it imports a helper function (read [Runtime `styleName` resolution](#runtime-stylename-resolution)). Therefore, you must install `babel-plugin-react-css-modules` as a direct dependency of the project.
287
288```bash
289npm install babel-plugin-react-css-modules --save
290```
291
292
293### React Native
294
295If you'd like to get this working in React Native, you're going to have to allow custom import extensions, via a `rn-cli.config.js` file:
296
297```js
298module.exports = {
299 getAssetExts() {
300 return ["scss"];
301 }
302}
303```
304
305Remember, also, that the bundler caches things like plugins and presets. If you want to change your `.babelrc` (to add this plugin) then you'll want to add the `--reset-cache` flag to the end of the package command.
306
307### Demo
308
309```bash
310git clone git@github.com:gajus/babel-plugin-react-css-modules.git
311cd ./babel-plugin-react-css-modules/demo
312npm install
313npm start
314```
315
316```bash
317open http://localhost:8080/
318```
319
320## Conventions
321
322### Anonymous reference
323
324Anonymous reference can be used when there is only one stylesheet import.
325
326Format: `CSS module name`.
327
328Example:
329
330```js
331import './foo1.css';
332
333// Imports "a" CSS module from ./foo1.css.
334<div styleName="a"></div>;
335```
336
337### Named reference
338
339Named reference is used to refer to a specific stylesheet import.
340
341Format: `[name of the import].[CSS module name]`.
342
343Example:
344
345```js
346import foo from './foo1.css';
347import bar from './bar1.css';
348
349// Imports "a" CSS module from ./foo1.css.
350<div styleName="foo.a"></div>;
351
352// Imports "a" CSS module from ./bar1.css.
353<div styleName="bar.a"></div>;
354```
355
356## Example transpilations
357
358### Anonymous `styleName` resolution
359
360When `styleName` is a literal string value, `babel-plugin-react-css-modules` resolves the value of `className` at the compile time.
361
362Input:
363
364```js
365import './bar.css';
366
367<div styleName="a"></div>;
368
369```
370
371Output:
372
373```js
374import './bar.css';
375
376<div className="bar___a"></div>;
377
378```
379
380### Named `styleName` resolution
381
382When a file imports multiple stylesheets, you must use a [named reference](#named-reference).
383
384> Have suggestions for an alternative behaviour?
385> [Raise an issue](https://github.com/gajus/babel-plugin-react-css-modules/issues/new?title=Suggestion%20for%20alternative%20handling%20of%20multiple%20stylesheet%20imports) with your suggestion.
386
387Input:
388
389```js
390import foo from './foo1.css';
391import bar from './bar1.css';
392
393<div styleName="foo.a"></div>;
394<div styleName="bar.a"></div>;
395```
396
397Output:
398
399```js
400import foo from './foo1.css';
401import bar from './bar1.css';
402
403<div className="foo___a"></div>;
404<div className="bar___a"></div>;
405
406```
407
408### Runtime `styleName` resolution
409
410When the value of `styleName` cannot be determined at the compile time, `babel-plugin-react-css-modules` inlines all possible styles into the file. It then uses [`getClassName`](https://github.com/gajus/babel-plugin-react-css-modules/blob/master/src/getClassName.js) helper function to resolve the `styleName` value at the runtime.
411
412Input:
413
414```js
415import './bar.css';
416
417<div styleName={Math.random() > .5 ? 'a' : 'b'}></div>;
418
419```
420
421Output:
422
423```js
424import _getClassName from 'babel-plugin-react-css-modules/dist/browser/getClassName';
425import foo from './bar.css';
426
427const _styleModuleImportMap = {
428 foo: {
429 a: 'bar__a',
430 b: 'bar__b'
431 }
432};
433
434<div styleName={_getClassName(Math.random() > .5 ? 'a' : 'b', _styleModuleImportMap)}></div>;
435
436```
437
438## Limitations
439
440* [Establish a convention for extending the styles object at the runtime](https://github.com/gajus/babel-plugin-react-css-modules/issues/1)
441
442## Have a question or want to suggest an improvement?
443
444* Have a technical questions? [Ask on Stack Overflow.](http://stackoverflow.com/questions/ask?tags=babel-plugin-react-css-modules)
445* Have a feature suggestion or want to report an issue? [Raise an issues.](https://github.com/gajus/babel-plugin-react-css-modules/issues)
446* Want to say hello to other `babel-plugin-react-css-modules` users? [Chat on Gitter.](https://gitter.im/babel-plugin-react-css-modules)
447
448## FAQ
449
450### How to migrate from react-css-modules to babel-plugin-react-css-modules?
451
452Follow the following steps:
453
454* Remove `react-css-modules`.
455* Add `babel-plugin-react-css-modules`.
456* Configure `.babelrc` (see [Configuration](#configuration)).
457* Remove all uses of the `cssModules` decorator and/or HoC.
458
459If you are still having problems, refer to one of the user submitted guides:
460
461* [Porting from react-css-modules to babel-plugin-react-css-modules (with Less)](http://www.jjinux.com/2018/04/javascript-porting-from-react-css.html)
462
463### How to reference multiple CSS modules?
464
465`react-css-modules` had an option [`allowMultiple`](https://github.com/gajus/react-css-modules#allowmultiple). `allowMultiple` allows multiple CSS module names in a `styleName` declaration, e.g.
466
467```js
468<div styleName='foo bar' />
469```
470
471This behaviour is enabled by default in `babel-plugin-react-css-modules`.
472
473### How to live reload the CSS?
474
475`babel-plugin-react-css-modules` utilises webpack [Hot Module Replacement](https://webpack.github.io/docs/hot-module-replacement.html) (HMR) to live reload the CSS.
476
477To enable live reloading of the CSS:
478
479* Enable [`webpackHotModuleReloading`](#configuration) `babel-plugin-react-css-modules` configuration.
480* Configure `webpack` to use HMR. Use [`--hot`](https://webpack.github.io/docs/webpack-dev-server.html) option if you are using `webpack-dev-server`.
481* Use [`style-loader`](https://github.com/webpack/style-loader) to load the style sheets.
482
483> Note:
484>
485> This enables live reloading of the CSS. To enable HMR of the React components, refer to the [Hot Module Replacement - React](https://webpack.js.org/guides/hmr-react/) guide.
486
487> Note:
488>
489> This is a [webpack](https://webpack.github.io/) specific option. If you are using `babel-plugin-react-css-modules` in a different setup and require CSS live reloading, raise an issue describing your setup.