nonzzz / vite-plugin-compression

vite plugin. compress your bundle file.
MIT License
171 stars 10 forks source link

Plugin Runs Before Processes Finish #45

Closed cemalgnlts closed 10 months ago

cemalgnlts commented 10 months ago

Hi,

After finishing the Vite operations, I minify the JSON files myself, but I cannot read the content of the JSON file because this plugin was working before.

nonzzz commented 10 months ago

I don't know why are you need to minify your JSON file after plugin done. Can you share your operational process?

cemalgnlts commented 10 months ago

I think I explained it wrong, this is my config file:

 {
  plugins: [
    AssetsMinifier(),
    compression({
      algorithm: "brotliCompress",
      deleteOriginalAssets: true,
      filename: "[path][base]" 
    })
  ];
}
function AssetsMinifier(): PluginOption {
  const exclude = [ /*...*/ ];

  return {
    name: "Assets Minifier",
    enforce: "pre",
    apply: "build",
    async closeBundle() {
      let assets = fastGlob.sync("./dist/**", {
        ignore: exclude,
      });

      assets = assets.filter((file) => /\.(html|css|js|json)$/.test(file));

      for (const filePath of assets) {
        let content = fs.readFileSync(filePath, "utf-8");

        if (/\.(js)$/.test(filePath)) {
          const { code } = /* ... */

          content = code;
        } else if (/\.(json)$/.test(filePath)) {
          content = JSON.stringify(JSONC.parse(content));
        } else if (/\.(css)$/.test(filePath)) {
          content = /* ... */
        }

        fs.writeFileSync(filePath, content, "utf-8");
      }

      console.log("Assets minified.");
    },
  };
}

compression is running before AssetsMinifier and that's why I can't operate on the encoded file.

nonzzz commented 10 months ago

This plugin runs most of task at generateBundle. Only the static file will be process at CloseBundle. So your plugin i think you can change the enfore order as post and put your plugin after this.

nonzzz commented 10 months ago

But after v0.11.0 vite-plugin-compression2 only work after vite:build-import-analysis If you want do some hack logic for bundleContext should also follow the way.

cemalgnlts commented 10 months ago

I used what you did here (index.ts#L155) and now I can minimize files before they are compressed.

Thanks.