drwpow / vite-plugin-bundlesize

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The plugin is incompatible without type: "module" in package.json

remixer-dec opened this issue · comments

I tried to use this plugin and got an error

Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules/vite-plugin-bundlesize/dist/plugin/index.js from vite.config.js not supported.
Instead change the require of index.js in vite.config.js to a dynamic import() which is available in all CommonJS modules.
    at Object._require.extensions.<computed> [as .js] (node_modules/vite/dist/node/chunks/dep-6305614c.js:63133:17)

there were no require() statements in vite.config.js nor in node_modules/vite-plugin-bundlesize/dist/plugin/index.js, so I was very confused about this error, the solution was adding "type": "module" in package.json, which caused a lot of errors related to postcss and tailwind module resolution, which I fixed via renaming them from js to cjs.

After fixing the issues, I was able to run the build command, but the file bundlemeta.json was nowhere to be found, because the plugin checks for hardcoded mode: "production" in vite options, instead of process.env.NODE_ENV.

Hopefully this info can help to save some time for people who run into similar issues.

Thanks for filing! And thanks for trying a beta plugin to help make it better.

There are 2 issues here, I think. The first is fixing a bug with CommonJS (legacy) projects—where there isn’t "type": "module" in package.json. In general, all modern Node projects should have this these days—it just runs Node in modern ESM JS. But I never want to list that as a requirement, because Vite wasn’t always running in modern ESM mode (v2 and earlier), and there are projects that can’t make this upgrade because of old dependencies. But I think this could be fixed within the package silently, without requiring people to add this.

The second issue about the production mode probably requires some documentation, and possibly a warning. I’m not sure why your build isn’t running in production mode, because none of the reported sizes will be accurate if it’s not. But that should fail loudly, or have some warning, or something. And the documentation should make this clearer when it runs.

I pushed a fix in v0.0.5 to fix the mode: "production" bug. Now it uses the Vite-recommended apply: 'build' (docs) for better results.

For the "type": "module" bug, I didn’t want to have to enforce this, but after digging into what it would take to support CommonJS as well, it would be too much. It would basically require maintaining 2 versions of this library, which is not in the cards for now. Since I’d recommend all users operate in "type": "module" just as a generally-better experience, I’ve added it to the docs as a requirement to use this plugin for now.

This resolves the two issues posted. Thanks again for giving this a try in the alpha stages, and please let me know if you encounter any more issues

Thank you