Coder Social home page Coder Social logo

babel-plugin-react-css-modules's Introduction

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.

babel-plugin-react-css-modules's People

Contributors

albertlucianto avatar andreascag avatar andris-silis avatar arashmotamedi avatar assertchris avatar benmvp avatar billy- avatar clessg avatar curtishumphrey avatar dsullivan7 avatar gajus avatar gbiryukov avatar gpittarelli avatar ianvs avatar j4chou avatar jcdekoning avatar jjinux avatar kamui avatar kilian avatar meglio avatar mvsmal avatar noriste avatar oscarbarrett avatar pbarbiero avatar pcreations avatar psykar avatar rohitrajendran avatar sthzg avatar trevorsmith avatar yume-chan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-plugin-react-css-modules's Issues

bug: unable to override localIdentName in css-loader settings. generateScopedName also doesn't work.

When I change

'css-loader?importLoader=1&modules&localIdentName=[path]___[name]__[local]___[hash:base64:5]'

to something mor suitable for me, like this:

'css-loader?importLoader=1&modules&localIdentName=[name]__[local]--[hash:6]'

I get unstyled component.

I've also tried to remove part of query string:

'css-loader?importLoader=1&modules'

and set pattern for generated names directly in babel-plugin-react-css-modules config:

'react-css-modules',
  {
    context,
    generateScopedName: '[path]___[name]__[local]___[hash:base64:5]'
  }

It doesn't work even with default value (I get unstyled component again).

I've encountered this problem in my own starter kit (and it takes me more than our to figure out what's going on 😠). But then I did the same in your demo, so to reproduce this bug just run it and try to specify some pattern other than default.

Versions:

{
  "private": true,
  "dependencies": {
    "babel-plugin-react-css-modules": "^2.1.3",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "webpack": "^2.2.0-rc.3"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-react-jsx": "^6.8.0",
    "css-loader": "^0.26.1",
    "style-loader": "^0.13.1",
    "webpack-dev-server": "^2.2.0-rc.0"
  }
}

Parse error: Unexpected token

I'm using browserify + gulp, and just tested with latest version 2.1.1, it fails with:

/Users/rico345100/Desktop/learn/browserifyTest/src/app.css:1
.table {
^
ParseError: Unexpected token

I just followed your example, it wasn't working at all with browserify + gulp.

This is gulp code:

gulp.task('default', () => {
	return browserify({
		entries: ['./src/app.js'],
		debug: true
	})
	.transform(babelify, { 
		presets: ["es2015", "react"],
		plugins: [
			"babel-plugin-react-css-modules",
		]
	})
	.bundle()
	.on('error', swallowError)
	.pipe(source('app.js'))
	.pipe(buffer())
	.pipe(gulp.dest('./build'));
});

and these are js codes:

import React from 'react';
import ReactDOM from 'react-dom';
import table from './app.css';

class App extends React.Component {
	render() {
		return (
			<div styleName='table.table'>
				<div styleName='table.row'>
					<div styleName='table.cell'>A1</div>
					<div styleName='table.cell'>B1</div>
					<div styleName='table.cell'>C1</div>
				</div>
			</div>
		);
	}
}

ReactDOM.render(
	<App />,
	document.getElementById('entry')
);
.table {
	display: table;
}

.row {
	display: table-row;
}

.cell {
	display: table-cell;
	padding: 5px;
}

.cell:nth-child(1) {
	background: #f00;
}

.cell:nth-child(2) {
	background: #0f0;
}

.cell:nth-child(3) {
	background: #00f;
}

.yellow {
	background: #ff0!important;
}

Any solution please?

Can't get this to work with less and sass

Im trying to use .scss files and .less files in the demo. however it doesn't seem to work.

Demo

I have only this react rendered component.
It uses a .css file, .less file and a .scss file.

AnonymouseStyleResolution.js

import React from 'react';
import table from './table.css';
import tableLess from './tableLess.less';
import tableScss from './tableScss.scss';

export default () => {
  return <div styleName='table.table'>
    <div styleName='table.row'>
      <div styleName='table.cell'>A0</div>
      <div styleName='tableLess.cell'>B0</div>
      <div styleName='tableScss.cell'>C0</div>
    </div>
  </div>;
};

i also have the 3 styles and they are exactly the same.

table.css, tableLess.less, tableScss.scss

.table {
  display: table;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 5px;
}

.cell:nth-child(1) {
  background: #f00;
}

.cell:nth-child(2) {
  background: #0f0;
}

.cell:nth-child(3) {
  background: #00f;
}

.yellow {
  background: #ff0!important;
}

This is my webpack config.

webpack.config.js

/* eslint-disable filenames/match-regex, import/no-commonjs */

const path = require('path');
const context = path.resolve(__dirname, 'src');

module.exports = {
  context,
  entry: './index.js',
  devtool: 'source-map',
  module: {
       loaders: [
      {
        include: path.resolve(__dirname, './src'),
        loaders: [
          'style-loader',
          'css-loader?importLoader=1&modules&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
        ],
        test: /\.css$/
      },
      { 
        include: path.resolve(__dirname, './src'),
        test: /\.less$/,
        loader: "style-loader!css-loader!less-loader" 
      },
      {
          test: /\.scss$/,
         loader: "style-loader!css-loader!sass-loader"
      },

      {
        include: path.resolve(__dirname, './src'),
        loader: 'babel-loader',
        query: {
          plugins: [
            'transform-react-jsx',
            ['react-css-modules', {
                context
            }],
            ['babel-plugin-react-css-modules',{
              context,
              filetypes:{
                ".less": "postcss-less",
                ".scss": "postcss-scss",
              }
            }],
          ]
        },
        test: /\.js$/
      }
    ]
  },
  output: {
    filename: '[name].js'
  }
};

Result

Only table.cell , table.row and table.table styles worked like they should. That is beacuse table is an import from a plain .css file.

By checking the DOM, the component seemed to have rendered correctly.

<div>
   <div class="components-___table__table___-8VwZ">
   <div class="components-___table__row___oUVuI">
   <div class="components-___table__cell___1Qm64">A0</div>
   <div class="components-___tableLess__cell___21Sqk">B0</div>
   <div class="components-___tableScss__cell___2tdLJ">C0</div></div>
</div>

However the style tags need to be modified as well from the source.
For some reason it seems to only work on the .css files.

Here are the style tags in the DOM:

This is the style genrerated from the .css file:

<style type="text/css">
.components-___table__table___-8VwZ {
  display: table;
}

.components-___table__row___oUVuI {
  display: table-row;
}

.components-___table__cell___1Qm64 {
  display: table-cell;
  padding: 5px;
}

.components-___table__cell___1Qm64:nth-child(1) {
  background: #f00;
}

.components-___table__cell___1Qm64:nth-child(2) {
  background: #0f0;
}

.components-___table__cell___1Qm64:nth-child(3) {
  background: #00f;
}

.components-___table__yellow___1MLje {
  background: #ff0!important;
}
</style>

This is the style genrerated from the .less and .scss files:

<style type="text/css">
.table {
  display: table;
}
.row {
  display: table-row;
}
.cell {
  display: table-cell;
  padding: 5px;
}
.cell:nth-child(1) {
  background: #f00;
}
.cell:nth-child(2) {
  background: #0f0;
}
.cell:nth-child(3) {
  background: #00f;
}
.yellow {
  background: #ff0!important;
}
</style>

Am I doing somthing wrong? Is somthing missing?

Nested styles don't work

An example

.nav {
  &-item {
    color: red;
  }
}
...
  Module build failed: Error: /path/to/my/component.js: CSS module does not exist.
...

I solved this problem by installing postcss-nested in

  /path/to/myproject/node_modules/babel-plugin-react-css-modules/

and added in requireCssModule.js

...
import ExtractImports from 'postcss-modules-extract-imports';
import LocalByDefault from 'postcss-modules-local-by-default';
import Parser from 'postcss-modules-parser';
import Scope from 'postcss-modules-scope';
import Values from 'postcss-modules-values';
import Nested from 'postcss-nested'; // add
...
const plugins = [
  Nested, // add (before or after Values)
  Values,
  LocalByDefault,
  ExtractImports,
  new Scope({
    generateScopedName: scopedName
  }),
  new Parser({
    fetch
  })
];
...

And all works well. But it would be nice to have native support.

Make unknown styles silently be ignored

When a class name is missing, it would be better if it simply did not add a class to the class list instead of failing.

This makes it hard to dynamically generate class names when iterating an array to ALLOW for targeting IF needed.

But as it stands now, you would have to define every possible class in the array in the style sheet as it's a hard failure if it doesn't find it.

This doesn't fit with what people expect of CSS.

Webpack 1.14 and Sass-loader

Is webpack 1.x and sass-loader supported? This is my configuration,

 // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel',
        query: {

          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/babel-loader/
          // directory for faster rebuilds.
          cacheDirectory: true,
          plugins: [
            'transform-react-jsx',
            [
              'react-css-modules',
              {
                "generateScopedName": "MYCOMP___[local]",
                "filetypes": {
                  ".scss": "postcss-scss"
                }
              }
            ]
          ]
        }
      },
      {
        test: /\.scss$/,
        include: path.resolve(__dirname, './stylesheets/sass'),
        loaders: [
          'style-loader?{"sourceMap":true,"attrs":{"id":"mycomp-style-tag"}}',
          'css-loader?modules=true&importLoaders=1&localIdentName=MYCOMP___[local]',
          'sass-loader?modules=true&importLoaders=1&localIdentName=MYCOMP___[local]',
          'autoprefixer-loader'
        ]
      },

and this is what package.json contains,


 "devDependencies": {
    "autoprefixer": "6.7.2",
    "node-sass": "^3.8.0",
    "sass-loader": "^4.0.0",
...
    "postcss-loader": "1.2.2",
    "postcss-scss": "^0.4.1",
...

Without sass-loader, my CSS and everything works fine. As I've tried to switch to use sass, I can see the CSS itself getting generated. But "styleName" is never defined.

That is, there is a <style id="mycomp-style-tag">... styles </style> tag in HEAD, but in the react component, all the elements don't get the right prefix.

What would you suggest doing?

browserify support?

When I run this module with browserify, it fails with:

Cannot read property 'replace' of undefined while parsing file:

Looks like there are same issues with Webpack, unfortunately no one uses browserify in this place :(
Anyway, some people like me, still prefer using Browserify + Gulp instead of Webpack.
Is there a way to solve this problem with Browserify now? If not, do you have plan to support it? I really impressed this module and really want to try with.

Thanks!

It's my gulp code:

gulp.task('default', () => {
	return browserify({
		entries: ['./src/app.js'],
		debug: true
	})
	.transform(babelify, { 
		presets: ["es2015", "react"],
		plugins: [
			"babel-plugin-react-css-modules",
		]
	})
	.bundle()
	.on('error', swallowError)
	.pipe(source('app.js'))
	.pipe(buffer())
	.pipe(gulp.dest('./build'));
});

Error details:

TypeError: /Users/rico345100/Desktop/learn/browserifyTest/src/app.js: Cannot read property 'replace' of undefined
    at generate (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/generic-names/index.js:29:23)
    at exportScopedName (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:48:24)
    at localizeNode (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:64:28)
    at Array.map (native)
    at localizeNode (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:60:38)
    at traverseNode (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:78:20)
    at Array.map (native)
    at traverseNode (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:84:38)
    at Array.map (native)
    at traverseNode (/Users/rico345100/Desktop/learn/browserifyTest/node_modules/postcss-modules-scope/lib/index.js:84:38)

Can't import css from node_modules

when doing something like import 'some-module/my.css'; babel plugin crashes with a message saying it can't find __dirname/some-module/my.css when it should be looking in ~/node_modules/some-module/my.css`

This is functionality that worked using ReactCSSModules

Establish a convention for extending the styles object at the runtime

react-css-modules uses styles property to overwrite the default component styles.

generateClassName could look for props.styles and this.props.styles when constructing the className value to determine whether a style needs to be overwritten.

There could be an option to force use of generateClassName even when styleName is a string literal value.

Adding "composes" doesn't update className

Let's say I have this code:

/* styles.css */
.center {
  text-align: center;
}
.block {
  background-color: white;
}
/* mycomponent.js */
import "styles.css"

render() {
  return <div styleName="block">
    hello world
  </div>
}

The output styles will be something like

...
<div class="styles-block_3XNkZ">...
...

Now if I add "composes"

/* styles.css */
.center {
  text-align: center;
}
.block {
  composes: center;
  background-color: white;
}

the component class remains the same (only has styles-block_3XNkZ). Even if I refresh page (f5) it will not help because webpack output js still has old css name (like):

// webpack output bundle
...
exports.locals = {
  "center": "styles-center_3l7jm",
  "block": "styles-block_3XNkZ"
};
...

If I change somehow the component it will trigger the changes, and the component will has the correct classes

...
<div class="styles-block_3XNkZ styles-center_3l7jm">...
...

I use

"webpack": "^2.2.0",
"webpack-dev-middleware": "^1.9.0",
"webpack-hot-middleware": "^2.15.0"

"babel-plugin-react-css-modules": "^2.2.0" (--save)

I tried https://github.com/gajus/babel-plugin-react-css-modules/tree/master/demo, and got the same
behavior.

Error with classnames package

Trying the babel plugin with the classnames package im getting errors:

captura de pantalla 2016-12-14 a las 17 48 23

the Button Component is so easy:

import React, { PropTypes } from 'react';
import classNames from 'classnames';

import './button.scss';

const Button = ({ className, href, type, alt, children, onClick }) => {
  var btnClass = classNames('button', className, {
    'default': type === 'default',
    'alt': type === 'alt'
  });

  return (
    <button
      styleName={btnClass}
      onClick={onClick}
    >
      {children}
    </button>
  );
};

export default Button;

Without the classname package its working fine:

import React, { PropTypes } from 'react';

import './button.scss';

const Button = ({ className, href, type, alt, children, onClick }) => {
  return (
    <button
      styleName="button default"
      onClick={onClick}
    >
      {children}
    </button>
  );
};

export default Button;

'undefined' className

// message.js
import './message.css';
function Message(props) {
  return <div className={props.className} styleName="message">message</div>;
}
render(<Message />);
// output from Babel with babel-plugin-react-css-modules
import './message.css';
function Message(props) {
  return <div className={props.className + ' message___3Hgmr'}>message</div>;
}
render(<Message />);

This outputs a div with className="undefined message___3Hgmr" because props.className is undefined.

A more robust output might look something like this:

// better output
import './message.css';
function Message(props) {
  return <div className={(props.className ? props.className + ' ' : '') + 'message___3Hgmr'}>message</div>;
}
render(<Message />);

stylus import support

import './index.module.styl'

got error:

Cannot use styleName attribute without importing at least one stylesheet.

`exclude` won't work with `require.context`

Hi,

I'll try to open a PR if I get no where, but I'd like to exclude a file from being transformed, but that file is required via require.context. when debugging, here is the output of stats when it tries to go over the file (config.js) that uses require.context:

PluginPass {
  _c: Map {},
  dynamicData: {},
  plugin:
   Plugin {
     _c: Map {},
     dynamicData: {},
     initialized: true,
     raw: {},
     key: 'react-css-modules',
     manipulateOptions: [Function: manipulateOptions],
     post: undefined,
     pre: undefined,
     visitor:
      { _exploded: {},
        _verified: {},
        ImportDeclaration: [Object],
        JSXElement: [Object],
        Program: [Object] } },
  key: 'react-css-modules',
  file:
   File {
     _c: Map {},
     dynamicData: {},
     pipeline: Pipeline {},
     log:
      Logger {
        filename: '/Users/mshertzberg/Gizmodo/kinja-components/.storybook/config.js',
        file: [Circular] },
     opts:
      { filename: '/Users/mshertzberg/Gizmodo/kinja-components/.storybook/config.js',
        filenameRelative: '/Users/mshertzberg/Gizmodo/kinja-components/.storybook/config.js',
        inputSourceMap: undefined,
        env: [Object],
        mode: undefined,
        retainLines: false,
        highlightCode: true,
        suppressDeprecationMessages: false,
        presets: [],
        plugins: [Object],
        ignore: [],
        only: undefined,
        code: true,
        metadata: true,
        ast: true,
        extends: undefined,
        comments: true,
        shouldPrintComment: undefined,
        wrapPluginVisitorMethod: undefined,
        compact: 'auto',
        minified: false,
        sourceMap: false,
        sourceMaps: false,
        sourceMapTarget: 'config.js',
        sourceFileName: '.storybook/config.js',
        sourceRoot: '/Users/mshertzberg/Gizmodo/kinja-components',
        babelrc: false,
        sourceType: 'module',
        auxiliaryCommentBefore: undefined,
        auxiliaryCommentAfter: undefined,
        resolveModuleSource: undefined,
        getModuleId: undefined,
        moduleRoot: '/Users/mshertzberg/Gizmodo/kinja-components',
        moduleIds: false,
        moduleId: undefined,
        passPerPreset: false,
        parserOpts: false,
        generatorOpts: false,
        basename: 'config' },
     parserOpts:
      { sourceType: 'module',
        sourceFileName: '/Users/mshertzberg/Gizmodo/kinja-components/.storybook/config.js',
        plugins: [Object] },
     pluginVisitors: [ [Object] ],
     pluginPasses: [ [Object] ],
     metadata: { usedHelpers: [], marked: [], modules: [Object] },
     dynamicImportTypes: {},
     dynamicImportIds: {},
     dynamicImports: [],
     declarations: {},
     usedHelpers: {},
     path:
      NodePath {
        parent: [Object],
        hub: [Object],
        contexts: [Object],
        data: {},
        shouldSkip: false,
        shouldStop: false,
        removed: false,
        state: undefined,
        opts: [Object],
        skipKeys: {},
        parentPath: null,
        context: [Object],
        container: [Object],
        listKey: undefined,
        inList: false,
        parentKey: 'program',
        key: 'program',
        node: [Object],
        scope: [Object],
        type: 'Program',
        typeAnnotation: null },
     ast:
      Node {
        type: 'File',
        start: 0,
        end: 722,
        loc: [Object],
        program: [Object],
        comments: [],
        tokens: [Object] },
     code: 'import \'preact/devtools\';\nimport {\n\tconfigure,\n\taddDecorator,\n\twithCentered,\n\twithKnobs,\n\tsetOptions\n} from \'../config/storybook\';\nimport { StyletronHOC } from \'../config/styletron\';\n\nfunction loadStories() {\n\tconst req = require.context(\'../components\', true, /story.js$/);\n\treq.keys().forEach(filename => req(filename));\n}\n\naddDecorator(getStory => <StyletronHOC>{getStory()}</StyletronHOC>);\naddDecorator(withCentered);\naddDecorator(withKnobs);\n\nsetOptions({\n\tname: \'kinja-components\',\n\turl: \'https://github.com/gawkermedia/kinja-components\',\n\tgoFullScreen: false,\n\tshowLeftPanel: true,\n\tshowDownPanel: true,\n\tshowSearchBox: false,\n\tdownPanelInRight: true,\n\tsortStoriesByKind: true\n});\n\nconfigure(loadStories, module);\n',
     shebang: '',
     hub: Hub { file: [Circular], options: undefined },
     scope:
      Scope {
        uid: 16,
        parent: null,
        hub: [Object],
        parentBlock: [Object],
        block: [Object],
        path: [Object],
        labels: [Object],
        references: [Object],
        bindings: [Object],
        globals: [Object],
        uids: {},
        data: {},
        crawling: false } },
  opts:
   { generateScopedName: '[hash:base64:10]',
     webpackHotModuleReloading: true,
     exclude: 'story',
     filetypes: { '.scss': 'postcss-scss' } } }

I would imagine this requires a PR to implement?

Thanks.

how to make a style global

How would you import a style globally?

I have this file, global.css

    .my-btn{color: red}

I want to be able to use class my-btn in every component in my project. How would you do that?

webpack2 - hash and path differ in css loader and bablerc

According to closed issue #4 generateScopedName should be added to .babelrc and its value should match the localIdentName of the css-loader.

However, when using the exact same value proposed there [path]___[name]__[local]___[hash:base64:5] for both, the value is not the same. The class on the element and the generated class name are not the same. Both the path and the hash parts of the strings differ, so the style is not applied.

The html element is:

<div class="src-collectors-containers-___Collectors__root___3x28u">test</div>

But the class in the style tag is:

.collectors-containers-___Collectors__root___2F0Qi {
  color: red; 
}

My webpack reads:

rules: [{
        test: /\.scss$/,
        loaders: [
          'style?sourceMap',
          'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
          'resolve-url',
          'sass?sourceMap'
        ]
      }
]

and my babelrc reads:

plugins: [
            [
              'react-css-modules',
              {
                generateScopedName: '[path]___[name]__[local]___[hash:base64:5]' 
              }
            ],
          ]

Just as in the examples, but it does not work.

Process className key in a destructured object

// message.js
import './message.css';
function Message(props) {
  return <div {...props} styleName="message">message</div>;
}
render(<Message className="message--mine" />);
/* message.css */
.message { ... }

The output looks like this:

import './message.css';
function Message(props) {
  return <div {...props} className="message___3Hgmr">message</div>;
}
render(<Message className="message--mine" />);

The className from props is overwritten, but I would like it to be included in the final className assignment since className was not specified on the div. I think getClassNames should accept a third parameter: every object that is destructured before the styleName attribute. getClassNames would iterate through these objects looking for className, then include whichever className appears last in the list of objects in the final className assignment.

Something like this:

import './message.css';
function Message(props) {
  return <div {...props} className={getClassName("message", map, props/*, other, destructured, objects */)}>message</div>;
}
render(<Message className="message--mine" />);
// outputs <div className="message--mine message___3Hgmr">message</div>

block global is not working

When I try this something like this below

:global{
	.page {color:blue}
	.container{color:red}
}

pageCompnent.js

import React from 'react'

import '../style/page.scss'
export default class Page extends React.Component {
	render() {
		return (
			<div className="page">
				{React.cloneElement(this.props.children, {...this.props})}
			</div>
		)
	}
}

The style color blue isn't applied to div.page. And then I checked bundle.css I got something like this

page_W3dy72 {
   color:blue
}

it seem like the :global was ignored

reproducing: https://github.com/craigcosmo/react-css-module-bug

Cannot react property 'name' of undefined

When using spread operator (and maybe other attribute that not might have a name property) to pass props from parent to children, the plugin fails since JSXSpreadAttribute does not have a name attribute, thus throwing an error when attempting to read the name property of this undefined value.

Cannot read property 'replace' of undefined

I'm running into the following issue while trying to use babel-plugin-react-css-modules@^1.1.0 with an experimental app I just created via create-react-app:

Failed to compile.

Error in ./src/components/calculator/index.js
Module build failed: TypeError: /Users/myuser/dev/sandbox/my-calculator-react-app/src/components/calculator/index.js: Cannot read property 'replace' of undefined
    at Array.map (native)
    at Array.map (native)
    at Array.map (native)
 @ ./src/containers/app-root/index.js 14:18-50

Here's my babel config:

{
  "presets": [
    "react-app"
  ],
  "plugins": [
    "react-css-modules"
  ]
}

Here's my webpack loaders config for my css & scss files:

{
  test: /\.css$/,
  loaders: [
    'style-loader?sourceMap',
    `css-loader?${JSON.stringify({
      importLoaders: 3,
      sourceMap: true,
      modules: true,
    })}`,
    'postcss-loader?sourceMap',
    "resolve-url-loader"
  ]
},
{
  test: /\.scss$/i,
  loaders: [
    'style-loader?sourceMap',
    `css-loader?${JSON.stringify({
      importLoaders: 3,
      sourceMap: true,
      modules: true,
    })}`,
    'postcss-loader?sourceMap',
    "resolve-url-loader",
    'sass-loader?sourceMap',
  ]
}

Here's a snippet of what my calculator.scss file looks like:

.calculator {
  display: block;
  padding: 0.2em 0.4em;
}

Here's my usage within my react component (and where the issue begins to occur):

import React, { Component } from 'react';
import './calculator.scss';// if i comment this line, the error goes away

class Calculator extends Component {
  render() {
    return (
      <div className="calculator">
        hi
      </div>
    );
  }
}

export default Calculator;

You can replicate this issue by cloning my repo: https://github.com/hulkish/calculator-app-exercise-react

Am I doing something wrong?

undefined class if both className and styleName are JSX expressions

Hi!
I want the parent component to be able to set classes on it's child components. Therefore I need the className to be appended at runtime. But this:

<div className={this.props.className} styleName={"foo"}>

Renders:

<div class="undefined foo___1ZSNk">

Even if the parent component passes className to the child component.

Thank you!

Named reference creating unused variables

I'm trying to use this plugin in my project. However, I got eslint "no-unused-variables" errors when I import css files and name them as variables.

Any ideas to fix this?

Plugin causing spread operator to fail in jsx

.babelrc

{
  "presets":[
    "react-app"
  ],
  "plugins":[
    [
      "react-css-modules",
      {
        "generateScopedName":"[path]___[name]__[local]___[hash:base64:5]"
      }
    ]
  ]
}

index.js

var test = <div {...something}></div>;

package.json
Minimal package.json can be provided if necessary 'reference' here.

Error

Module build failed: TypeError: xxx: Cannot read property 'name' of undefined

Support for cssnext and postcss plugins

Hello,

I have this in webpack.config.js:

			...
			// Styles
			{
				test: /\.css$/,
				use: [
					{ loader: 'style-loader' },
					{
						loader: 'css-loader',
						options: {
							modules: true,
							importLoaders: 2,
							localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
						}
					},
					{ loader: 'resolve-url-loader' },
					{ loader: 'postcss-loader' }
				]
			},
			...

This in .babelrc:

	...
	"plugins": [
		["transform-object-rest-spread", { "useBuiltIns": true }],
		["react-css-modules", { "generateScopedName": "[path]___[name]__[local]___[hash:base64:5]" }]
	],
	...

And this postcss.config.js:

module.exports = ctx => ({
	parser: false,
	map: ctx.env === 'development' ? 'inline' : false,
	from: ctx.from,
	to: ctx.to,
	plugins: {
		'postcss-cssnext': {},
		doiuse: {
			browsers: ['last 2 versions', '> 1%']
		},
		cssnano: ctx.env === 'production' ? {} : false
	}
});

I can see the transformed classes in generated CSS but get CSS module cannot be resolved. error while running WebPack.

Should it work or is a new feature ?

As a quick hack I found this trick works:

.box {
	display: flex;
}

.profile {

	&__name {
		color: red;
	}

	&__avatar {

		&__image {
		}
	}
}

.profile__name {/* Only to define name in import */}
.profile__avatar {/* Only to define name in import */}
.profile__avatar__image {/* Only to define name in import */}

Allow empty string to be passed to styleName.

I have a use case where I conditionally want to apply a style, e.g.

<div styleName={isReady : 'ready' : ''}>
  ...
</div>

Currently there's no way to accomplish this, because the plugin will explode looking for a CSS module that uses an empty string. Is there a way to short-circuit this case and give up?

Make babel-plugin-react-css-modules work with commonjs require

Hello,

when requiring scss files using require() syntax I get Cannot use styleName attribute without importing at least one stylesheet.. However if I switch to using import it works (minus an eslint parsing error).

I'm trying to introduce css-modules into an old code base. I have the es6 babel preset running (that's why imports work), but code is linted without modules support and I would love to keep it that way for the time being. Is there anyway to make this plugin work with require?

This plugin should not take over webpack's native module resolve

one of my webpack property looks like this

resolve: {
	modulesDirectories: [
		"app",
		"app/test",
		"app/component",
                "app/css"
                "app/css/custom"
	]
},

I set up webpack config like that, so I can do this

import React from 'react'
import 'normalize.scss' // locates app/css folder
import 'flexboxgrid.scss' // locates app/css folder
import 'ui.scss' // locates app/css/custom folder


export default class Page extends React.Component {
	render() {
		return (
			<div className="page">
				{React.cloneElement(this.props.children, {...this.props})}
			</div>
		)
	}
}

It was perfect for my need. Until I installed babel-plugin-react-css-modules to my project.

Now When I do this

import React from 'react'
import a from 'normalize.scss' // locates app/css folder
import b from 'flexboxgrid.scss' // locates app/css folder
import d from 'ui.scss' // locates app/css/custom folder

export default class Page extends React.Component {
	render() {
		return (
			<div className="page">
				{React.cloneElement(this.props.children, {...this.props})}
			</div>
		)
	}
}

I got a bunch of errors like below

./app/component/Page.js
Module build failed: Error: /Users/craigcosmo/Desktop/clean 2/app/component/Page.js: ENOENT: no such file or directory, open '/Users/craigcosmo/Desktop/clean 2/app/component/normalize.scss'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at fs.readFileSync (fs.js:508:33)
    at getTokens (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-plugin-react-css-modules/src/requireCssModule.js:34:14)
    at exports.default (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-plugin-react-css-modules/src/requireCssModule.js:77:10)
    at PluginPass.ImportDeclaration (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-plugin-react-css-modules/src/index.js:86:71)
    at newFn (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/index.js:114:17)
    at traverse (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-traverse/lib/index.js:79:12)
    at File.transform (/Users/craigcosmo/Desktop/clean 2/node_modules/babel-core/lib/transformation/file/index.js:558:35)
    at /Users/craigcosmo/Desktop/clean 2/node_modules/babel-core/lib/transformation/pipeline.js:50:19
 @ ./app/component/MainContainer.js 15:12-27

As you can see now, webpack doesn't know where my modules are.

webpack+babel+typescript Module build failed: TypeError Cannot read property 'replace' of undefined

My config is: typescript+babel loaders with webpack.
I added the plugin to .babelrc
I'm importing css file as

import "./../../App.css";

And get this error:

ERROR in ./src/client/Streaming/components/Share/index.tsx
Module build failed: TypeError: /Users/diegolaciar/workspace/collide-react-web/src/client/Streaming/components/Share/index.tsx: Cannot read property 'replace' of undefined
    at generate (/Users/diegolaciar/workspace/collide-react-web/node_modules/generic-names/index.js:29:23)
    at exportScopedName (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:48:24)
    at localizeNode (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:64:28)
    at Array.map (native)
    at localizeNode (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:60:38)
    at traverseNode (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:78:20)
    at Array.map (native)
    at traverseNode (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:84:38)
    at Array.map (native)
    at traverseNode (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:84:38)
    at /Users/diegolaciar/workspace/collide-react-web/node_modules/postcss-modules-scope/lib/index.js:103:25
    at /Users/diegolaciar/workspace/collide-react-web/node_modules/postcss/lib/container.js:241:28
    at /Users/diegolaciar/workspace/collide-react-web/node_modules/postcss/lib/container.js:148:26
    at Root.each (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss/lib/container.js:114:22)
    at Root.walk (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss/lib/container.js:147:21)
    at Root.walkRules (/Users/diegolaciar/workspace/collide-react-web/node_modules/postcss/lib/container.js:239:25)
 @ ./src/client/Streaming/App.tsx 34:13-42

thanks,

Cannot get server-side rendering without webpack to work

I have created a fork (see #68) with the basic setup that should be necessary to get this plugin to work in a server-side rendering environment without webpack, e.g. with renderToString. The plugin does get run, but then throws this error:

❯ npm run -s server-example
/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babel-core/lib/transformation/file/index.js:590
      throw err;
      ^

SyntaxError: /Users/lawrence/Code/babel-plugin-react-css-modules/demo/src/components/table.css: Unexpected token (1:0)
> 1 | .table {
    | ^
  2 |   display: table;
  3 | }
  4 |
    at Parser.pp$5.raise (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:4373:13)
    at Parser.pp.unexpected (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:1716:8)
    at Parser.pp$3.parseExprAtom (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3683:12)
    at Parser.parseExprAtom (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:7016:22)
    at Parser.pp$3.parseExprSubscripts (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3427:19)
    at Parser.pp$3.parseMaybeUnary (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3407:19)
    at Parser.pp$3.parseExprOps (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3337:19)
    at Parser.pp$3.parseMaybeConditional (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3314:19)
    at Parser.pp$3.parseMaybeAssign (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:3277:19)
    at Parser.parseMaybeAssign (/Users/lawrence/Code/babel-plugin-react-css-modules/demo/node_modules/babylon/lib/index.js:6242:20)

Am I misunderstanding how to use this plugin? Any help you can offer is greatly appreciated!

Unknown props in Enzyme/Jest

Not sure if this is the old questions.

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>;
  }
}

As the example posted, this works great, but if I want to test this table, by using

const component = shallow(<Table />);
component.html();

I get unknown styleName props console warning. I wonder is there any ways to mute this warning apart from stripping down prop name by using spread operator.

Thanks

can there be better error handling?

I have jsx like this

<div styleName="home">
	<div styleName="header">
	</div>
</div>

if I have missing class .header in my stylesheet, I will will get very generic error. I have no idea that I'm missing .header. Is there way to specify which class is missing?

Wrong Installation instructions for demo

I'm trying to test the demo on this page:

https://github.com/gajus/babel-plugin-react-css-modules/tree/master/demo

So, I created a new folder and from the console I first this:

git clone [email protected]:gajus/babel-plugin-react-css-modules.git

This give me this error:

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So, to bypass this error I just manually download the zip file and extract the demo folder.

Next I run ... npm install

This one goes well ...

And finally I run:

webpack-dev-server

and I get:

command not found

What are the right instructions to run the demo?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.