docd27/rollup-plugin-glsl-optimize

ERROR: require an ES module from a CommonJS file

Closed this issue · 2 comments

I'm trying to use your plugin and get the following error:

Error: While loading the Rollup configuration from "rollup.config.js", Node tried to require an ES module from a CommonJS file, which is not supported. A common cause is if there is a package.json file with "type": "module" in the same folder. You can try to fix this by changing the extension of your configuration file to ".cjs" or ".mjs" depending on the content, which will prevent Rollup from trying to preprocess the file but rather hand it to Node directly.

changing my config file to mjs did not work because then I can't import variables from package.json (because the json rollup plugin no longer gets transpiled for the config).

Any tips for how I can get this to work?

It's worth clarifying this isn't an issue with this plugin specifically but more of a general rollup config issue (see rollup/rollup#3443)

The best approach is native ESM within a .mjs rollup config.
You can read the rollup documentation which suggests approaches for importing json files:

  • Use native ESM json imports. Unfortunately currently flagged in node so you need to run rollup with node --experimental-json-modules ./node_modules/.bin/rollup
import packageConfig from './package.json';
// And once node has Import Assertions you'll also be able to:
import packageConfig from './package.json' assert { type: 'json' };
  • Just read the file directly JSON.parse(fs.readFileSync('path/to/package.json'))
  • Write a load-package.cjs wrapper with module.exports = require('./package.json'); and import that

At any rate this plugin was developed with native ESM since it's 2021 and matches the trajectory of other plugins and the wider JS ecosystem. Supporting legacy CJS whilst possible would entail extra complexity and transpilation.

thanks for clarifying, I did find that documentation but couldn't get it to work :-) will try fixing it with your suggestions. I'll close this issue.