npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

simplify-css-modules-webpack-plugin

v1.1.0

Published

Simplify your CSS Modules

Downloads

20

Readme

simplify-css-modules-webpack-plugin

npm Build status

⚠️ Use with caution: this plugin is experimental! ⚠️

Installation

yarn add -D simplify-css-modules-webpack-plugin

Usage

// webpack.config.js
const SimplifyCssModulesPlugin = require("simplify-css-modules-webpack-plugin");

module.exports = {
  module: {
    rules: {
      test: /\.module.css$/i,
      use: [
        ...
        {
          loader: "css-loader",
          options: {
            esModule: true,
            modules: {
              // It's important to prefix your css-loader's localIdentName with
              // the plugin's "magic prefix" so that it's easier for the plugin
              // to identify css modules.
              localIdentName: `${SimplifyCssModulesPlugin.magicPrefix}[hash:base64]`
            }
          }
        }
      ]
    }
  },
  ...
  plugins: [new SimplifyCssModulesPlugin()]
};

It's also strongly recommended to enable the esModule: true option on both css-loader and the mini-css-extract-plugin loader. Doing so should produce smaller tree-shaken js and css bundles.

See the config we generate in tests for an example.

Options

| Name | Type | Default | Description | |---------------------|-----------|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | mangle | {Boolean} | true | Whether the plugin should mangle css module classnames to short alternatives (overrides your localIdentName) | | prune | {Boolean} | true | Whether the plugin should remove unused css rules based on classes seen in your output js | | mappingFilePath | {String} | undefined | If set, stores a mapping of mangled classnames to the target location. Recommended when running multiple builds that need the same classnames (e.g. a separate SSR build) |

Behaviour

The plugin will run on the js and css files produced by your build. It will run after assets have been optimised (i.e. after terser/other minifiers have run).

If it identifies CSS Modules, it will reduce the size of classnames via mangling and update the importing js file.

As a second step, any classnames that were not found referenced in the js files in the chunk will be purged from the css file.

Why?

Unique, short selectors

Enabled by the mangle option!

CSS Modules are great, but one problem they face is that it's possible to end up with the same rule in two different chunks depending on your splitChunks settings or use of dynamic imports.

If this happens, and the rule is loaded-in lazily (via a dynamic import), it can break styling of the page due to re-applying styles to any existing elements with that className, due to the way css specificity works (based on the rule order, not the html classname order).

More aggressive tree-shaking

Enabled by the prune option!

It's tricky to fully tree-shake css modules without resorting to running a tool like PurgeCSS on your output files. The built-in options of esModule on both css-loader and the mini-css-extract-plugin loader provide some help, but leave behind unused rules in the extracted css files themselves.

Since we're iterating over the css module rules and finding connections between the js files that import from them, we can perform an additional pass using this information to remove unused rules that we otherwise wouldn't know about.

Under the hood, we use PurgeCSS, but directly pass it the list of classnames that we know we saw during the mangle pass. This way, we don't have to write a custom extractor and can be sure that only module classname rules will be removed.

Known limitations

css-loader / mini-css-extract-plugin inlining of class mappings

It's common for css-loader to export the entire mapping of classnames -> module class names into the js file importing them. If this happens, mangling will still take place but no classes will be pruned from the css file.

This css-loader issue tracks a potential fix for some of these cases.

Dynamic classname lookups

Any code that needs to look up the generated classname at runtime will run into the same problem as above: the bundle will include the entire mapping, which will signal to this plugin that every classname is "used".

Where possible, avoid dynamic classname lookups. E.g.

import styles from './styles.css';

// Avoid: entire classname mapping is required in the bundle
const myVar = Math.random() > 0.5 ? 'containerV1' : 'containerV2';
console.log(styles[myVar]);

// Prefer: styles can be inlined by terser, which removes the mapping and allows the classes
// to be pruned entirely from the css file by this plugin
const myStyle = Math.random() > 0.5 ? styles.containerV1 : styles.containerV2;
console.log(myStyle);

In both cases the mangling logic in the plugin will work, but the latter case will lead to smaller js and css bundles.