0
votes

How can use CSS modules in production and load standard css file in production?

I am configuring an new application with React using webpack

In development I use CSS modules using webpack loaders :

into my .jsx file I import the style file:

import style from './stile.scss';
export class App extends React.Component {
 render() {
    return (
        <div>
            <div>
                <span className={style.title}>Ciao</span>
            </div>
        </div>
    )
 }
}

then I use the following webpack configuration for loaders for my stylesheets:

loaders: [
 {
   test: /\.(scss|css)$/,
  loader: 'style-loader!css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap'
  }
]

this way everything works (the style is included in the .js file and classes properly hased)

but in production? I should leave the browser render all the classes included in the webpack bundle.js output file?

I would rather create a css file with webpack (and ExtracttextPlugin) with all my style:

 {
     test: /\.(css|scss)$/,
     loader: ExtractTextPlugin.extract('css-loader' )
 }

and link the .css produced in my index.html

Problem is that now all my classes definitions into the React components are no longer rendered in the browser.

How should I solve this?

1

1 Answers

2
votes

You can't just switch from using CSS modules to not using them, that doesn't work out as your code depends on it. Also there is no reason not to use CSS modules in production as well. What you want to change is not the CSS modules, but the way you include the CSS. Instead of having it in your JavaScript bundle you can extract them with extract-text-webpack-plugin into a separate .css file, but you still need to use the same configuration for the loaders.

webpack 1

{
  test: /\.(css|scss)$/,
  loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap')
}

The first argument style-loader is only used as a fallback if the CSS can't be extracted.

webpack 2

The arguments to ExtractTextPlugin.extract changed and for readability using options instead of an inline query in the string.

{
  test: /\.(css|scss)$/,
  loader: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use:  [
      {
        loader: 'css-loader',
        options: {
          sourceMap: true,
          modules: true,
          importLoaders: 1,
          localIdentName: '[name]-[local]___[hash:base64:5]'
        }
      },
      { loader: 'sass-loader', options: { sourceMap: true } }
    ]
  })
}