theKashey / used-styles

📝All the critical styles you've used to render a page.
MIT License
138 stars 10 forks source link

Correct rules order #26

Open theKashey opened 3 years ago

theKashey commented 3 years ago

Right now documentation proposed the following way to intent the "right" order of styles

// with chunk format [chunkhash]_[id] lower ids are potentialy should be defined before higher
const styleData = discoverProjectStyles(resolve('build'), name => {
  // get ID of a chunk and use it as order hint
  const match = name.match(/(\d)_c.css/);
  return match && +match[1];
});

which is generally not correct, even if working in the majority of the use cases.

theKashey commented 3 years ago

A way to make it right - to use webpack-imported

import { stylesheetCorrectOrder } from "webpack-imported/css";
import configuration from './build/imported.json'; // <<---- generate file using WebpackImportedPlugin

// get  all css files
const cssFiles = configuration.assets
    .filter((asset) => asset.type === "css")
    .map(({ name }) => name);

// map to chunks
const cssToChunk = Object.entries(configuration.chunkMap).reduce((acc, [key, value]) => {
    if (value.css) {
        value.css.forEach((css) => {
            acc[css] = key;
        });
    }

    return acc;
}, {} as Record<string, string>);

// "correct order", list all chunks in the prority webpack will list them
// __ this line is the main deal breaker here __
const order = stylesheetCorrectOrder(configuration);

// generate style data
const styleData = discoverProjectStyles(process.env.PUBLIC_DIR!, (name) => {
    const asset = cssFiles.find((clientAsset) => name.includes(clientAsset));

    if (asset && cssToChunk[asset]) {
        return order.indexOf(cssToChunk[asset]);
    }

    return false;
});