Node 14 ES Module: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: xo.config.js
See original GitHub issueIt seems impossible to load a JavaScript configuration when package.json contains "type": "module"
.
In my project, there are complex conditions that necessitates using a JavaScript (not JSON) configuration, xo.config.js
.
Recently I’m upgrading my project to ES Modules by adding "type": "module"
in package.json.
However, xo
attempts to load xo.config.js
using require()
, and Node.js thinks it’s a module that can only be loaded with import()
, thus throwing error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/user/project/xo.config.js
require() of ES modules is not supported.
require() of /home/user/project/xo.config.js from /home/user/project/node_modules/cosmiconfig/dist/loaders.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename xo.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/user/project/package.json.
It does not matter whether xo.config.js
is written as ES Module or CommonJS.
Since removing "type": "module"
is not an acceptable option, I tried renaming to xo.config.cjs
, but xo
does not load the configuration and is using its default configuration.
package.json
{
"private": true,
"type": "module",
"scripts": {
"lint": "xo --fix"
},
"devDependencies": {
"xo": "^0.30.0"
}
}
xo.config.js or xo.config.cjs
module.exports = {
rules: {
'object-curly-spacing': ['error', 'always']
}
};
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (6 by maintainers)
cosmiconfig default
searchPlaces
includes .cjs extension: https://github.com/davidtheclark/cosmiconfig/blob/18346056c9a7fdf8d7531ea5a998edfb255fc140/src/index.ts#L111-L121XO overrides it with a list that excludes .cjs extension: https://github.com/xojs/xo/blob/7629ce0e887bce9f056eda4300602f90ce2f89bb/lib/constants.js#L118-L124
I think cosmiconfig’s intention is that XO should use
packageProp: "xo"
and not overridesearchPlaces
.@sindresorhus cosmiconfig 7 supposedly supports the .cjs extension, but XO doesn’t. You can see that the tests here ignored the config and therefore fail: https://github.com/sindresorhus/refined-github/pull/4002
My current solution is to just use
.xo-config.json
instead