TransWikia.com

Angular custom webpack config enable CSS modules

Stack Overflow Asked by grinay on December 1, 2021

I’m trying to apply CSS modules concept agains my angular app, to order embed it into existing frontend with CSS which unfortunately overlaps. My project uses scss, I want webpack “modulize” my CSS after CSS if formed from scss on last build step I think.

I want to use CSS loader of webpack to achieve this.
But I couldn’t make it work.

https://www.npmjs.com/package/@angular-builders/custom-webpack
to order customize my webpack config.
I’ve tried to apply the next configuration

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/i,
        loader: 'css-loader',
        options: {
          modules: true,
        },
      },
    ],
  },
};

and got this error

ERROR in Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError

(1:1) Unknown word

> 1 | exports = module.exports = require("../../../../css-loader/dist/runtime/api.js")(false);

I’ve tried to find and add css loader into existing

module.exports = (config, options) => {

  const rules = config.module.rules || [];
  rules.forEach(rule => {
    if (String(rule.test) === String(/.css$/)) {

      rule.use.push({ loader: 'css-loader', options: { modules: true }})

    }
  });
  return config;
};

Getting the same error. How to make it work?

Update 1:

I found that angular uses postcss which also provides this functionality as a plugin, postcss-modules. Also still can’t make it work.

One Answer

I was able to implement CSS Modules in Angular with the help of @angular-builders/custom-webpack as you suggested.

However, my solution use postcss-modules and posthtml-css-modules instead of the css-loader to hash the styles.

postcss-modules hash all the styles, then posthtml-css-modules replaces the class names on the html files by the hashed class names.

I documented my solution here:

I hope it will be useful for you.

Answered by German Quinteros on December 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP