• Stars
    star
    2,044
  • Rank 21,660 (Top 0.5 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Transforms styleName to className using compile time CSS module resolution.

babel-plugin-react-css-modules

Travis build status NPM version Canonical Code Style Gitter Twitter Follow

Looking for maintainers

This project is not actively maintained by the original author. However, I am happy to nominate new maintainers. If you wish to contribute to babel-plugin-react-css-modules, please begin by raising PRs that fix existing issues. PRs must pass CI/CD tests, include tests (if they change behavior or fix a bug), and include documentation.

Transforms styleName to className using compile time CSS module resolution.

In contrast to react-css-modules, babel-plugin-react-css-modules has a lot smaller performance overhead (0-10% vs +50%; see Performance) and a lot smaller size footprint (less than 2kb vs 17kb react-css-modules + lodash dependency).

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 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 to be precise). To see CSS Modules in practice, webpack-demo.

In the context of React, CSS Modules look like this:

import React from 'react';
import styles from './table.css';

export default class Table extends React.Component {
  render () {
    return <div className={styles.table}>
      <div className={styles.row}>
        <div className={styles.cell}>A0</div>
        <div className={styles.cell}>B0</div>
      </div>
    </div>;
  }
}

Rendering the component will produce a markup similar to:

<div class="table__table___32osj">
  <div class="table__row___2w27N">
    <div class="table__cell___1oVw5">A0</div>
    <div class="table__cell___1oVw5">B0</div>
  </div>
</div>

and a corresponding CSS file that matches those CSS classes.

Awesome!

However, there are several disadvantages of using CSS modules this way:

  • You have to use camelCase CSS class names.
  • You have to use styles object whenever constructing a className.
  • Mixing CSS Modules and global CSS classes is cumbersome.
  • Reference to an undefined CSS Module resolves to undefined without a warning.

babel-plugin-react-css-modules automates loading of CSS Modules using styleName property, e.g.

import React from 'react';
import './table.css';

export default class Table extends React.Component {
  render () {
    return <div styleName='table'>
      <div styleName='row'>
        <div styleName='cell'>A0</div>
        <div styleName='cell'>B0</div>
      </div>
    </div>;
  }
}

Using babel-plugin-react-css-modules:

  • You are not forced to use the camelCase naming convention.

  • You do not need to refer to the styles object every time you use a CSS Module.

  • There is clear distinction between global CSS and CSS modules, e.g.

    <div className='global-css' styleName='local-module'></div>

Difference from react-css-modules

react-css-modules introduced a convention of using styleName attribute to reference CSS module. react-css-modules is a higher-order 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?). However, this approach has a measurable performance penalty (see Performance).

babel-plugin-react-css-modules solves the developer experience problem without impacting the performance.

Performance

The 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.

Note: This benchmark suite does not include a scenario when babel-plugin-react-css-modules can statically construct a literal value at the build time. If a literal value of the className is constructed at the compile time, the performance is equal to the base benchmark.

Name Operations per second (relative margin of error) Sample size Difference from the base benchmark
Using className (base) 9551 (Β±1.47%) 587 -0%
react-css-modules 5914 (Β±2.01%) 363 -61%
babel-plugin-react-css-modules (runtime, anonymous) 9145 (Β±1.94%) 540 -4%
babel-plugin-react-css-modules (runtime, named) 8786 (Β±1.59%) 527 -8%

Platform info:

  • Darwin 16.1.0 x64
  • Node.JS 7.1.0
  • V8 5.4.500.36
  • NODE_ENV=production
  • Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz Γ— 8

View the ./benchmark.

Run the benchmark:

git clone [email protected]:gajus/babel-plugin-react-css-modules.git
cd ./babel-plugin-react-css-modules
npm install
npm run build
cd ./benchmark
npm install
NODE_ENV=production ./test

How does it work?

  1. Builds index of all stylesheet imports per file (imports of files with .css or .scss extension).
  2. Uses postcss to parse the matching CSS files into a lookup of CSS module references.
  3. Iterates through all JSX element declarations.
  4. Parses the styleName attribute value into anonymous and named CSS module references.
  5. Finds the CSS class name matching the CSS module reference:
    • If styleName value is a string literal, generates a string literal value.
    • If styleName value is a jSXExpressionContainer, uses a helper function (getClassName) to construct the className value at the runtime.
  6. Removes the styleName attribute from the element.
  7. Appends the resulting className to the existing className value (creates className attribute if one does not exist).

Configuration

Configure the options for the plugin within your .babelrc as follows:

{
  "plugins": [
    ["react-css-modules", {
      "option": "value"
    }]
  ]
}

Options

Name Type Description Default
context string Must match webpack context configuration. css-loader inherits context values from webpack. Other CSS module implementations might use different context resolution logic. process.cwd()
exclude string A RegExp that will exclude otherwise included files e.g., to exclude all styles from node_modules exclude: 'node_modules'
filetypes ?FiletypesConfigurationType Configure postcss syntax loaders like sugarss, LESS and SCSS and extra plugins for them.
generateScopedName ?GenerateScopedNameConfigurationType Refer to Generating scoped names. If you use this option, make sure it matches the value of localIdentName in webpack config. See this issue [path]___[name]__[local]___[hash:base64:5]
removeImport boolean Remove the matching style import. This option is used to enable server-side rendering. false
webpackHotModuleReloading boolean Enables hot reloading of CSS in webpack false
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. "throw"
attributeNames ?AttributeNameMapType Refer to Custom Attribute Mapping {"styleName": "className"}
skip boolean Whether to apply plugin if no matching attributeNames found in the file false
autoResolveMultipleImports boolean Allow multiple anonymous imports if styleName is only in one of them. false

Missing a configuration? Raise an issue.

Note: The default configuration should work out of the box with the css-loader.

Option types (flow)

type FiletypeOptionsType = {|
  +syntax: string,
  +plugins?: $ReadOnlyArray<string | $ReadOnlyArray<[string, mixed]>>
|};

type FiletypesConfigurationType = {
  [key: string]: FiletypeOptionsType
};

type GenerateScopedNameType = (localName: string, resourcePath: string) => string;

type GenerateScopedNameConfigurationType = GenerateScopedNameType | string;

type AttributeNameMapType = {
  [key: string]: string
};

Configurate syntax loaders

To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:

  1. Add the postcss syntax loader as a development dependency:
npm install postcss-scss --save-dev
  1. Add a filetypes syntax mapping to the Babel plugin configuration. For example for SCSS:
"filetypes": {
  ".scss": {
    "syntax": "postcss-scss"
  }
}

And optionally specify extra plugins:

"filetypes": {
  ".scss": {
    "syntax": "postcss-scss",
    "plugins": [
      "postcss-nested"
    ]
  }
}

NOTE: postcss-nested is added as an extra plugin for demonstration purposes only. It's not needed with postcss-scss because SCSS already supports nesting.

Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config:

  "plugins": [
    ["postcss-import-sync2", {
      "path": ["src/styles", "shared/styles"]
    }],
    "postcss-nested"
  ]

Custom Attribute Mapping

You can set your own attribute mapping rules using the attributeNames option.

It's an object, where keys are source attribute names and values are destination attribute names.

For example, the <NavLink> component from React Router has a activeClassName attribute to accept an additional class name. You can set "attributeNames": { "activeStyleName": "activeClassName" } to transform it.

The 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.

Installation

When babel-plugin-react-css-modules cannot resolve CSS module at a compile time, it imports a helper function (read Runtime styleName resolution). Therefore, you must install babel-plugin-react-css-modules as a direct dependency of the project.

npm install babel-plugin-react-css-modules --save

React Native

If 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:

module.exports = {
  getAssetExts() {
    return ["scss"];
  }
}

Remember, 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.

Demo

git clone [email protected]:gajus/babel-plugin-react-css-modules.git
cd ./babel-plugin-react-css-modules/demo
npm install
npm start
open http://localhost:8080/

Conventions

Anonymous reference

Anonymous reference can be used when there is only one stylesheet import.

Format: CSS module name.

Example:

import './foo1.css';

// Imports "a" CSS module from ./foo1.css.
<div styleName="a"></div>;

Named reference

Named reference is used to refer to a specific stylesheet import.

Format: [name of the import].[CSS module name].

Example:

import foo from './foo1.css';
import bar from './bar1.css';

// Imports "a" CSS module from ./foo1.css.
<div styleName="foo.a"></div>;

// Imports "a" CSS module from ./bar1.css.
<div styleName="bar.a"></div>;

Example transpilations

Anonymous styleName resolution

When styleName is a literal string value, babel-plugin-react-css-modules resolves the value of className at the compile time.

Input:

import './bar.css';

<div styleName="a"></div>;

Output:

import './bar.css';

<div className="bar___a"></div>;

Named styleName resolution

When a file imports multiple stylesheets, you must use a named reference.

Have suggestions for an alternative behaviour? Raise an issue with your suggestion.

Input:

import foo from './foo1.css';
import bar from './bar1.css';

<div styleName="foo.a"></div>;
<div styleName="bar.a"></div>;

Output:

import foo from './foo1.css';
import bar from './bar1.css';

<div className="foo___a"></div>;
<div className="bar___a"></div>;

Runtime styleName resolution

When 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 helper function to resolve the styleName value at the runtime.

Input:

import './bar.css';

<div styleName={Math.random() > .5 ? 'a' : 'b'}></div>;

Output:

import _getClassName from 'babel-plugin-react-css-modules/dist/browser/getClassName';
import foo from './bar.css';

const _styleModuleImportMap = {
  foo: {
    a: 'bar__a',
    b: 'bar__b'
  }
};

<div styleName={_getClassName(Math.random() > .5 ? 'a' : 'b', _styleModuleImportMap)}></div>;

Limitations

Have a question or want to suggest an improvement?

FAQ

How to migrate from react-css-modules to babel-plugin-react-css-modules?

Follow the following steps:

  • Remove react-css-modules.
  • Add babel-plugin-react-css-modules.
  • Configure .babelrc (see Configuration).
  • Remove all uses of the cssModules decorator and/or HoC.

If you are still having problems, refer to one of the user submitted guides:

How to reference multiple CSS modules?

react-css-modules had an option allowMultiple. allowMultiple allows multiple CSS module names in a styleName declaration, e.g.

<div styleName='foo bar' />

This behaviour is enabled by default in babel-plugin-react-css-modules.

How to live reload the CSS?

babel-plugin-react-css-modules utilises webpack Hot Module Replacement (HMR) to live reload the CSS.

To enable live reloading of the CSS:

Note:

This enables live reloading of the CSS. To enable HMR of the React components, refer to the Hot Module Replacement - React guide.

Note:

This is a webpack 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.

I get a "Cannot use styleName attribute for style name '[X]' without importing at least one stylesheet." error

First, ensure that you are correctly importing the CSS file following the conventions.

If you are correctly importing but using different CSS (such as SCSS), this is likely happening because your CSS file wasn't able to be successfully parsed. You need to configure a syntax loader.

I get a "Could not resolve the styleName '[X]' error but the class exists in the CSS included in the browser.

First, verify that the CSS is being included in the browser. Remove from styleName the reference to the CSS class that's failing and view the page. Search through the <style> tags that have been added to the <head> and find the one related to your CSS module. Copy the code into your editor and search for the class name.

Once you've verified that the class is being rendered in CSS, the likely cause is that the babel-plugin-react-css-modules is unable to find your CSS class in the parsed code. If you're using different CSS (such as SCSS), verify that you have configured a syntax loader.

However, if you're using a syntaxes such as postcss-scss or postcss-less, they do not compile down to CSS. So if you are programmatically building a class name (see below), webpack will be able to generate the rendered CSS from SCSS/LESS, but babel-plugin-react-css-modules will not be able to parse the SCSS/LESS.

A SCSS example:

$scales: 10, 20, 30, 40, 50;

@each $scale in $scales {
  .icon-#{$scale} {
    width: $scale;
    height: $scale;
  }
  }

babel-plugin-react-css-modules will not receive icon-10 or icon-50, but icon-#{$scale}. That is why you receive the error that styleName "icon-10" cannot be found.

More Repositories

1

react-css-modules

Seamless mapping of class names to CSS modules inside of React components.
JavaScript
5,232
star
2

slonik

A Node.js PostgreSQL client with runtime and build time type safety, and composable SQL.
TypeScript
4,356
star
3

swing

A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder.
JavaScript
2,618
star
4

redux-immutable

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.
TypeScript
1,880
star
5

eslint-plugin-flowtype

Flow type linting rules for ESLint.
JavaScript
1,078
star
6

prepack-webpack-plugin

A webpack plugin for prepack.
JavaScript
1,041
star
7

eslint-plugin-jsdoc

JSDoc specific linting rules for ESLint.
JavaScript
1,024
star
8

roarr

JSON logger for Node.js and browser.
TypeScript
1,024
star
9

turbowatch

Extremely fast file change detector and task orchestrator for Node.js.
TypeScript
901
star
10

table

Formats data into a string table.
TypeScript
871
star
11

usus

Webpage pre-rendering service. ⚑️
JavaScript
805
star
12

flow-runtime

A runtime type system for JavaScript with full Flow compatibility.
JavaScript
802
star
13

surgeon

Declarative DOM extraction expression evaluator. πŸ‘¨β€βš•οΈ
JavaScript
693
star
14

liqe

Lightweight and performant Lucene-like parser, serializer and search engine.
TypeScript
611
star
15

eslint-config-canonical

The most comprehensive ES code style guide.
JavaScript
536
star
16

write-file-webpack-plugin

Forces webpack-dev-server to write bundle files to the file system.
JavaScript
528
star
17

lightship

Abstracts readiness, liveness and startup checks and graceful shutdown of Node.js services running in Kubernetes.
TypeScript
514
star
18

gitdown

GitHub markdown preprocessor.
JavaScript
445
star
19

xhprof.io

GUI to analyze the profiling data collected using XHProf – A Hierarchical Profiler for PHP.
PHP
429
star
20

contents

Table of contents generator.
JavaScript
416
star
21

brim

View (minimal-ui) manager for iOS 8.
JavaScript
391
star
22

global-agent

Global HTTP/HTTPS proxy agent configurable using environment variables.
TypeScript
341
star
23

youtube-player

YouTube iframe API abstraction.
JavaScript
340
star
24

react-aux

A self-eradicating component for rendering multiple elements.
JavaScript
328
star
25

http-terminator

Gracefully terminates HTTP(S) server.
TypeScript
318
star
26

isomorphic-webpack

Abstracts universal consumption of application code base using webpack.
JavaScript
291
star
27

scream

Dynamic viewport management for mobile. Manage viewport in different states of device orientation. Scale document to fit viewport. Calculate the dimensions of the "minimal" iOS 8 view relative to your viewport width.
JavaScript
289
star
28

create-index

Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.
JavaScript
279
star
29

graphql-deduplicator

A GraphQL response deduplicator. Removes duplicate entities from the GraphQL response.
JavaScript
278
star
30

gajus.com-blog

The contents of the http://gajus.com/blog/.
JavaScript
226
star
31

wholly

jQuery plugin used to select the entire table row and column in response to mouseenter and mouseleave events. Wholly supports table layouts that utilize colspan and rowspan.
JavaScript
204
star
32

puppeteer-proxy

Proxies Puppeteer Page requests.
JavaScript
195
star
33

canonical-reducer-composition

Spec for Canonical Reducer Composition design pattern.
188
star
34

angular-swing

AngularJS directive for Swing: A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder, and many others.
JavaScript
182
star
35

dindent

HTML indentation library for development and testing.
PHP
177
star
36

babel-plugin-graphql-tag

Compiles GraphQL tagged template strings using graphql-tag.
JavaScript
172
star
37

vlad

Input validation library promoting succinct syntax with extendable validators and multilingual support.
PHP
104
star
38

babel-plugin-log-deprecated

Adds a console.warn statement to the functions annotated with @deprecated tag.
JavaScript
103
star
39

redux-immutable-examples

A complete application showing use of redux-immutable.
JavaScript
103
star
40

eslint-plugin-canonical

ESLint rules for Canonical ruleset.
TypeScript
98
star
41

babel-preset-es2015-webpack

Babel preset for all es2015 plugins except babel-plugin-transform-es2015-modules-commonjs.
JavaScript
97
star
42

scalpel

A CSS selector parser.
JavaScript
95
star
43

eslint-plugin-sql

SQL linting rules for ESLint.
TypeScript
88
star
44

graphql-lazyloader

GraphQL directive that adds Object-level data resolvers.
TypeScript
88
star
45

orientationchangeend

The orientationchangeend event is fired when the orientation of the device has changed and the associated rotation animation has been complete.
JavaScript
78
star
46

bugger

Bugger is a collection of functions for debugging PHP code.
CSS
77
star
47

planton

Database-agnostic task scheduler.
TypeScript
77
star
48

pg-formatter

A PostgreSQL SQL syntax beautifier.
TypeScript
76
star
49

dora

Input generation library for value resolution, data persistence, templates, CSRF and protection from XSS.
CSS
73
star
50

react-css-modules-examples

Usage examples for react-css-modules.
JavaScript
72
star
51

format-graphql

Formats GraphQL schema definition language (SDL) document.
JavaScript
70
star
52

to-string-loader

to-string loader for webpack
JavaScript
64
star
53

interdependent-interactive-histograms

This is a helper function that utilises d3.js and Crossfilter to create interdependent interactive histograms.
JavaScript
60
star
54

extract-email-address

Extracts email address from an arbitrary text input.
JavaScript
59
star
55

babel-plugin-transform-function-composition

Syntactic sugar 🍧🍨🍦 for easy to read function composition. πŸ¦„
JavaScript
58
star
56

preoom

Retrieves & observes Kubernetes Pod resource (CPU, memory) utilisation.
JavaScript
55
star
57

fuss

The Facebook SDK for PHP provides an interface to the Graph API.
PHP
53
star
58

postloader

A scaffolding tool for projects using DataLoader, Flow and PostgreSQL.
JavaScript
51
star
59

moa

MOA implements dynamically generated Active Record database abstraction.
PHP
50
star
60

extract-date

Extracts date from an arbitrary text input.
JavaScript
49
star
61

gitinfo

Gets information about a Git repository.
JavaScript
47
star
62

sister

Foundation for your emitter implementation. 202 reasons to not write your own implementation of event emitter.
JavaScript
45
star
63

react-outside-event

A higher order React component that attaches an event listener for events that occur outside of the component element.
JavaScript
44
star
64

babel-plugin-annotate-console-log

Annotates console.log call expression with information about the invocation context.
JavaScript
42
star
65

react-youtube-player

React component that encapsulates YouTube IFrame Player API and exposes player controls using the component properties.
JavaScript
40
star
66

bundle-dependencies

Generates bundledDependencies package.json value using values of the dependencies property. Updates package.json definition using the generated bundledDependencies value.
JavaScript
39
star
67

facebook-friend-rank

PHP class that can calculate who are the best user's friends. Data accuracy depends on the user activity and granted permissions.
PHP
39
star
68

waitehr

Waits for HTTP response and retries request until the expected response is received.
TypeScript
36
star
69

doll

Extended PDO with inline type hinting, deferred connection support, logging and benchmarking.
PHP
36
star
70

pie-chart

This is a helper function that utilises d3.js to create pie charts.
JavaScript
36
star
71

sguid

Signed Globally Unique Identifier (SGUID) generator.
JavaScript
34
star
72

prepack-loader

A webpack loader for prepack.
JavaScript
31
star
73

slonik-utilities

Utilities for manipulating data in PostgreSQL database using Slonik.
TypeScript
31
star
74

seeql

Real-time SQL profiler.
JavaScript
31
star
75

react-strict-prop-types

A higher order component that raises an error if component is used with an unknown property.
JavaScript
29
star
76

crack-json

Extracts all JSON objects from an arbitrary text document.
JavaScript
29
star
77

paggern

Pattern interpreter for generating random strings.
PHP
28
star
78

cluster-map

Abstracts execution of tasks in parallel using Node.js cluster.
JavaScript
27
star
79

roarr-cli

A CLI program for processing Roarr logs.
TypeScript
26
star
80

database-types

A generic type generator for various databases.
JavaScript
26
star
81

iapetus

Prometheus metrics server.
TypeScript
25
star
82

postgres-bridge

postgres/pg compatibility layer
TypeScript
25
star
83

roarr-browser-log-writer

Roarr log writer for use in a web browser.
TypeScript
23
star
84

require-new

Requires a new module object.
JavaScript
23
star
85

pan

Touch enabled implementation of WHATWG drag and drop mechanism.
JavaScript
23
star
86

tmdb

The Movie Database (TMDb) SDK.
JavaScript
22
star
87

pragmatist

A collection of tasks to standardize builds.
JavaScript
21
star
88

pianola

A declarative function composition and evaluation engine.
JavaScript
20
star
89

eslint-plugin-zod

Zod linting rules for ESLint.
TypeScript
20
star
90

approximate-now

Approximate (fast) current UNIX time.
TypeScript
20
star
91

babel-plugin-transform-export-default-name

Babel plugin that transforms default exports to named exports.
JavaScript
20
star
92

xfetch

A light-weight HTTP client for Node.js.
JavaScript
19
star
93

extract-time

Extracts time from an arbitrary text input.
JavaScript
19
star
94

override-require

Overrides Node.js module resolution logic.
JavaScript
18
star
95

fastify-webpack-hot

A Fastify plugin for serving files emitted by Webpack with Hot Module Replacement (HMR).
TypeScript
18
star
96

babel-plugin-lodash-modularize

Babel plugin that replaces lodash library import statement to individual module imports.
JavaScript
18
star
97

canonical

Canonical code style linter and formatter for JavaScript, SCSS, CSS and JSON.
JavaScript
18
star
98

semantic-url-parser

Extracts content information from known URL patterns.
TypeScript
17
star
99

extract-price

Extracts prices from an arbitrary text input.
JavaScript
17
star
100

async-request

async-request is a wrapper for request that uses ES7 async functions.
JavaScript
16
star