webpackpreactcss-loaderpreact-cli

Preact change webpack css loader config


I'd like to change the webpack config on Preact to have only hashed class names, and make them shorter as well if it's a safe practice.

The css loader works fine on my preact project but sometimes the component is visible in the class names even though the modules.css file is referenced by that component alone.

https://github.com/preactjs/preact-cli/wiki/Config-Recipes#setting-proxy-for-dev-server-using-config-directly

I've came across this documentation but I'm not experienced enough to get this to work and I'm looking for the specific code to write in my preact.config.js


Solution

  • The following config should be what you're after, but let me know if you have any issues with it:

    // preact.config.js
    
    /**
     * @param {import('preact-cli').Config} config - original webpack config
     * @param {import('preact-cli').Env} env - current environment and options pass to the CLI
     * @param {import('preact-cli').Helpers} helpers - object with useful helpers for working with the webpack config
     */
    export default (config, env, helpers) => {
        const { loader: cssLoader } = helpers.getLoadersByName(config, 'css-loader')[0];
        cssLoader.options.modules.localIdentName = '[hash:base64:5]';
    }
    

    The general idea here is that we get the css-loader using preact-cli's config helpers (documented here), but specifically the first one; the first is for CSS Modules, or the CSS you author in components/ and routes/. The second css-loader instance is for all other CSS you author, which won't be hashed, so we'll ignore it and only get the first ([0]).

    Then, we simply update the options. The default value can be found here, and we simply alter it to only use the hash, dropping the local__ part.

    Regarding making the hashes shorter, I would not. Any shorter and you drastically increase the chances of triggering a collision in caches.