Skip to content

Commit

Permalink
fix: support export default null
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jun 17, 2024
1 parent 85555be commit 81d2dbd
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) {

Check warning on line 38 in src/import.ts

View check run for this annotation

Codecov / codecov/patch

src/import.ts#L38

Added line #L38 was not covered by tests
// 兼容 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 81d2dbd

Please sign in to comment.