webpack css-loader, style-loader default config loader overrides

When using loaders in webpack, you can specify them both in the require/import statement as well as the webpack config file. Typically, you configure them in the webpack file:
module: {
        loaders: [
     {
  test: /\.css$/,
  use: [
   {loader: "style-loader"},
   {loader: "css-loader", options: { module: true, camelCase: true}}],
            },
            {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel-loader'
            },
 {
      test: /\.(jpe?g|png|gif|svg)$/i,
      loaders: [
         'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
         'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
       ]
  }]
    },
This is my module section in this particual webpack.config.js file. Note the module: true which indicates that my CSS class names and identifiers will be scrambled to create "local" names. This is helpful when you want to avoid global CSS name clashes--a very common problem.
However, you can also specify them inline. I was using react-virtualized, which needs to include the react-virtualized/styles.css file to ensure that they are included:
import 'react-virtualized/styles.css';
The problem is that if the "module" mode of css-loader is being used, the react-virtualized classnames will be mangled and the react-virtualized components will not "find" them.
The secret is to load the react-virtualized styles without using the module option. I first tried:
import 'style-loader!css-loader?module=false!react-virtualized/styles.css';
But I received an error:
...
ERROR in ./~/css-loader?module=false!./~/style-loader!./~/css-loader?{"module":true,"camelCase":true}!./~/react-virtualized/styles.css
Module build failed: Unknown word (5:1)
  3 | // load the styles
  4 | var content = require("!!../css-loader/index.js?{\"module\":true,\"camelCase\":true}!./styles.css");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
    | ^
  6 | // add the styles to the DOM
  7 | var update = require("!../style-loader/addStyles.js")(content, {});
  8 | if(content.locals) module.exports = content.locals;

 @ ./~/style-loader!./~/css-loader?module=false!./~/react-virtualized/styles.css 4:14-133
 ...
The key is that the additional loaders specified in the import statement (or require if you use that) are ADDED to the loaders in the webconfig file. We really need to override the webconfig file for this particular load.
The answer was easy, although hard to find:
import '!style-loader!css-loader?module=false!react-virtualized/styles.css';
The ! at the start indicates that the loaders in webpack.config.js should not be used and only the loaders in the import statement should apply.

Comments

Popular posts from this blog

quick note on scala.js, react hooks, monix, auth

zio environment and modules pattern: zio, scala.js, react, query management

user experience, scala.js, cats-effect, IO