Skip to content

Commit

Permalink
fix: support export default null (#22)
Browse files Browse the repository at this point in the history
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved compatibility with CommonJS modules simulating ES modules by
updating condition checks when importing modules.

- **Tests**
- Added test cases to support scenarios where modules have `null` as the
default export.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
fengmk2 authored Jun 17, 2024
1 parent 85555be commit 61a8a98
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
}
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/cjs/module-exports-null.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = null;
1 change: 1 addition & 0 deletions test/fixtures/esm/export-default-null.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default null;
24 changes: 24 additions & 0 deletions test/import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});

0 comments on commit 61a8a98

Please sign in to comment.