Skip to content

Commit 82bf823

Browse files
authored
Fix ESM support in Node 22+ when the package includes the main property (#648)
* fix(package-json): loadPlugin - check if `require` returns a ESM module * chore(package-json): loadPlugin - add `istanbul ignore next` to avoid coverage error
1 parent 6607e5b commit 82bf823

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

lib/package-json.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,20 @@ async function loadPackageJson(path: string): Promise<PackageJson> {
3535
export async function loadPlugin(path: string): Promise<Plugin> {
3636
const pluginRoot = getPluginRoot(path);
3737
try {
38-
// Try require first which should work for CJS plugins.
39-
return require(pluginRoot) as Plugin; // eslint-disable-line import/no-dynamic-require
38+
/**
39+
* Try require first which should work for CJS plugins.
40+
* From Node 22 requiring on ESM module returns the module object
41+
* @see https://github.com/bmish/eslint-doc-generator/issues/615
42+
*/
43+
type cjsOrEsmPlugin = Plugin | { __esModule: boolean; default: Plugin };
44+
// eslint-disable-next-line import/no-dynamic-require
45+
const _plugin = require(pluginRoot) as cjsOrEsmPlugin;
46+
47+
/* istanbul ignore next */
48+
if ('__esModule' in _plugin && _plugin.__esModule && _plugin.default) {
49+
return _plugin.default;
50+
}
51+
return _plugin as Plugin;
4052
} catch (error) {
4153
// Otherwise, for ESM plugins, we'll have to try to resolve the exact plugin entry point and import it.
4254
const pluginPackageJson = await loadPackageJson(path);

test/lib/generate/cjs-test.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,7 @@ describe('generate (cjs)', function () {
6262

6363
describe('package.json `main` field points to non-existent file', function () {
6464
it('throws an error', async function () {
65-
const FIXTURE_PATH = join(
66-
'test',
67-
'fixtures',
68-
'cjs-main-file-does-not-exist',
69-
);
65+
const FIXTURE_PATH = join(FIXTURE_ROOT, 'cjs-main-file-does-not-exist');
7066
await expect(generate(FIXTURE_PATH)).rejects.toThrow(
7167
/Cannot find module/u,
7268
);

0 commit comments

Comments
 (0)