UNPKG

18.8 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 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://babeljs.io/docs/en/next/babel-types.html#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.js.org/configuration/entry-context/#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 sugarss, 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|`skip`|`boolean`|Whether to apply plugin if no matching `attributeNames` found in the file|`false`|
202|`autoResolveMultipleImports`|`boolean`|Allow multiple anonymous imports if `styleName` is only in one of them.|`false`|
203
204Missing a configuration? [Raise an issue](https://github.com/gajus/babel-plugin-react-css-modules/issues/new?title=New%20configuration:).
205
206> Note:
207> The default configuration should work out of the box with the [css-loader](https://github.com/webpack/css-loader).
208
209#### Option types (flow)
210
211```js
212type FiletypeOptionsType = {|
213 +syntax: string,
214 +plugins?: $ReadOnlyArray<string | $ReadOnlyArray<[string, mixed]>>
215|};
216
217type FiletypesConfigurationType = {
218 [key: string]: FiletypeOptionsType
219};
220
221type GenerateScopedNameType = (localName: string, resourcePath: string) => string;
222
223type GenerateScopedNameConfigurationType = GenerateScopedNameType | string;
224
225type AttributeNameMapType = {
226 [key: string]: string
227};
228
229```
230
231### Configurate syntax loaders
232
233To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:
234
2351. Add the [postcss syntax loader](https://github.com/postcss/postcss#syntaxes) as a development dependency:
236
237 ```bash
238 npm install postcss-scss --save-dev
239 ```
240
2412. Add a filetype syntax mapping to the Babel plugin configuration
242
243 ```json
244 "filetypes": {
245 ".scss": {
246 "syntax": "postcss-scss"
247 }
248 }
249 ```
250
251 And optionaly specify extra plugins
252
253 ```json
254 "filetypes": {
255 ".scss": {
256 "syntax": "postcss-scss",
257 "plugins": [
258 "postcss-nested"
259 ]
260 }
261 }
262 ```
263
264 Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config
265
266 ```json
267 "plugins": [
268 ["postcss-import-sync2", {
269 "path": ["src/styles", "shared/styles"]
270 }],
271 "postcss-nested"
272 ]
273 ```
274
275
276### Custom Attribute Mapping
277
278You can set your own attribute mapping rules using the `attributeNames` option.
279
280It's an object, where keys are source attribute names and values are destination attribute names.
281
282For 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.
283
284The 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.
285
286## Installation
287
288When `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.
289
290```bash
291npm install babel-plugin-react-css-modules --save
292```
293
294
295### React Native
296
297If 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:
298
299```js
300module.exports = {
301 getAssetExts() {
302 return ["scss"];
303 }
304}
305```
306
307Remember, 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.
308
309### Demo
310
311```bash
312git clone git@github.com:gajus/babel-plugin-react-css-modules.git
313cd ./babel-plugin-react-css-modules/demo
314npm install
315npm start
316```
317
318```bash
319open http://localhost:8080/
320```
321
322## Conventions
323
324### Anonymous reference
325
326Anonymous reference can be used when there is only one stylesheet import.
327
328Format: `CSS module name`.
329
330Example:
331
332```js
333import './foo1.css';
334
335// Imports "a" CSS module from ./foo1.css.
336<div styleName="a"></div>;
337```
338
339### Named reference
340
341Named reference is used to refer to a specific stylesheet import.
342
343Format: `[name of the import].[CSS module name]`.
344
345Example:
346
347```js
348import foo from './foo1.css';
349import bar from './bar1.css';
350
351// Imports "a" CSS module from ./foo1.css.
352<div styleName="foo.a"></div>;
353
354// Imports "a" CSS module from ./bar1.css.
355<div styleName="bar.a"></div>;
356```
357
358## Example transpilations
359
360### Anonymous `styleName` resolution
361
362When `styleName` is a literal string value, `babel-plugin-react-css-modules` resolves the value of `className` at the compile time.
363
364Input:
365
366```js
367import './bar.css';
368
369<div styleName="a"></div>;
370
371```
372
373Output:
374
375```js
376import './bar.css';
377
378<div className="bar___a"></div>;
379
380```
381
382### Named `styleName` resolution
383
384When a file imports multiple stylesheets, you must use a [named reference](#named-reference).
385
386> Have suggestions for an alternative behaviour?
387> [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.
388
389Input:
390
391```js
392import foo from './foo1.css';
393import bar from './bar1.css';
394
395<div styleName="foo.a"></div>;
396<div styleName="bar.a"></div>;
397```
398
399Output:
400
401```js
402import foo from './foo1.css';
403import bar from './bar1.css';
404
405<div className="foo___a"></div>;
406<div className="bar___a"></div>;
407
408```
409
410### Runtime `styleName` resolution
411
412When 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.
413
414Input:
415
416```js
417import './bar.css';
418
419<div styleName={Math.random() > .5 ? 'a' : 'b'}></div>;
420
421```
422
423Output:
424
425```js
426import _getClassName from 'babel-plugin-react-css-modules/dist/browser/getClassName';
427import foo from './bar.css';
428
429const _styleModuleImportMap = {
430 foo: {
431 a: 'bar__a',
432 b: 'bar__b'
433 }
434};
435
436<div styleName={_getClassName(Math.random() > .5 ? 'a' : 'b', _styleModuleImportMap)}></div>;
437
438```
439
440## Limitations
441
442* [Establish a convention for extending the styles object at the runtime](https://github.com/gajus/babel-plugin-react-css-modules/issues/1)
443
444## Have a question or want to suggest an improvement?
445
446* Have a technical questions? [Ask on Stack Overflow.](http://stackoverflow.com/questions/ask?tags=babel-plugin-react-css-modules)
447* Have a feature suggestion or want to report an issue? [Raise an issues.](https://github.com/gajus/babel-plugin-react-css-modules/issues)
448* Want to say hello to other `babel-plugin-react-css-modules` users? [Chat on Gitter.](https://gitter.im/babel-plugin-react-css-modules)
449
450## FAQ
451
452### How to migrate from react-css-modules to babel-plugin-react-css-modules?
453
454Follow the following steps:
455
456* Remove `react-css-modules`.
457* Add `babel-plugin-react-css-modules`.
458* Configure `.babelrc` (see [Configuration](#configuration)).
459* Remove all uses of the `cssModules` decorator and/or HoC.
460
461If you are still having problems, refer to one of the user submitted guides:
462
463* [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)
464
465### How to reference multiple CSS modules?
466
467`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.
468
469```js
470<div styleName='foo bar' />
471```
472
473This behaviour is enabled by default in `babel-plugin-react-css-modules`.
474
475### How to live reload the CSS?
476
477`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.
478
479To enable live reloading of the CSS:
480
481* Enable [`webpackHotModuleReloading`](#configuration) `babel-plugin-react-css-modules` configuration.
482* Configure `webpack` to use HMR. Use [`--hot`](https://webpack.github.io/docs/webpack-dev-server.html) option if you are using `webpack-dev-server`.
483* Use [`style-loader`](https://github.com/webpack/style-loader) to load the style sheets.
484
485> Note:
486>
487> 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.
488
489> Note:
490>
491> 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.