5

As far as I know, CSS loader outputs CommonJS, which doesn't work with some of Webpack's optimization features. Is there a way to make CSS loader output ES modules (import/export)?

Edit:

Here's what happens with ES modules:

main.js

import { FOO } from './module';
console.log(FOO);

output

var FOO = 'foo';
console.log(FOO);

And with CSS loader:

main.js

import { foo } from './styles.scss';
console.log(foo);

output

38: (function(module, exports, __webpack_require__) {
    module.exports = {"foo":"a"};
}),
...
var styles = __webpack_require__(38);
console.log(test["foo"]);
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • Can you please update as to which version of webpack and css-loader are you actually using? – Nagaraj Tantri Oct 06 '19 at 00:47
  • Which version supports them? I'm using css-loader 3.0.0 and webpack 4.35.0 – Leo Jiang Oct 06 '19 at 08:26
  • Then it's already supported according to their update in [here](https://github.com/webpack-contrib/css-loader/issues/612). Using css-loader with `https://github.com/postcss/postcss-loader` will help you get the required output. In case you are not getting it, can you please show the code? – Nagaraj Tantri Oct 06 '19 at 11:02
  • @LeoJiang, +1 thank you for this question! I don't know how to help you but I've had a lot of fun learning about CSS loader with this [Quick & Easy CSS Loaders](https://www.youtube.com/watch?v=BwhTKJFpKSw) – costargc Oct 07 '19 at 20:31
  • I already have postcss-loader, I added the output I see – Leo Jiang Oct 08 '19 at 05:05

1 Answers1

1

Try using the post-css loader for this:

$ npm install -D postcss-loader

Then in your webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { importLoaders: 1 } },
          'postcss-loader'
        ]
      }
    ]
  }
}
Vince
  • 3,207
  • 1
  • 17
  • 28