diff --git a/src/import.ts b/src/import.ts index 393c54c..5121f3d 100644 --- a/src/import.ts +++ b/src/import.ts @@ -35,7 +35,7 @@ export async function importModule(filepath: string, options?: ImportModuleOptio // commonjs obj = require(moduleFilePath); debug('[importModule] require %o => %o', filepath, obj); - if (obj?.__esModule === true && obj?.default) { + if (obj?.__esModule === true && 'default' in obj) { // 兼容 cjs 模拟 esm 的导出格式 // { // __esModule: true, @@ -72,7 +72,7 @@ export async function importModule(filepath: string, options?: ImportModuleOptio obj = obj.default; } if (options?.importDefaultOnly) { - if (obj.default) { + if ('default' in obj) { obj = obj.default; } } diff --git a/test/fixtures/cjs/module-exports-null.js b/test/fixtures/cjs/module-exports-null.js new file mode 100644 index 0000000..b894a23 --- /dev/null +++ b/test/fixtures/cjs/module-exports-null.js @@ -0,0 +1 @@ +module.exports = null; diff --git a/test/fixtures/esm/export-default-null.js b/test/fixtures/esm/export-default-null.js new file mode 100644 index 0000000..7646bbd --- /dev/null +++ b/test/fixtures/esm/export-default-null.js @@ -0,0 +1 @@ +export default null; diff --git a/test/import.test.ts b/test/import.test.ts index 085e3c5..6d2e3cb 100644 --- a/test/import.test.ts +++ b/test/import.test.ts @@ -83,5 +83,29 @@ describe('test/import.test.ts', () => { assert.equal(obj.foo, 'bar'); assert.equal(obj.one, 1); }); + + it('should support module.exports = null', async () => { + assert.equal(await importModule(getFilepath('cjs/module-exports-null.js'), { + importDefaultOnly: true, + }), null); + assert.equal(await importModule(getFilepath('cjs/module-exports-null'), { + importDefaultOnly: true, + }), null); + assert.equal((await importModule(getFilepath('cjs/module-exports-null'), { + importDefaultOnly: false, + })).default, null); + }); + + it('should support export default null', async () => { + assert.equal(await importModule(getFilepath('esm/export-default-null.js'), { + importDefaultOnly: true, + }), null); + assert.equal(await importModule(getFilepath('esm/export-default-null'), { + importDefaultOnly: true, + }), null); + assert.equal((await importModule(getFilepath('esm/export-default-null.js'), { + importDefaultOnly: false, + })).default, null); + }); }); });