From 2eefcbc22337a36e1d97792f8e51eb1fdba95e0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=8E=E9=B8=A1=E6=B2=A1=E5=90=8D?= Date: Sun, 8 Oct 2023 12:57:20 +0800 Subject: [PATCH] fix: always export `default` --- src/generate-export.ts | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/generate-export.ts b/src/generate-export.ts index 943b318..01071a5 100644 --- a/src/generate-export.ts +++ b/src/generate-export.ts @@ -10,9 +10,14 @@ export function generateExport(analyzed: Analyzed): ExportsRuntime | null { return null } - const memberDefault = analyzed.exports - // Find `module.exports` or `exports.default` - .find(exp => exp.token.left === 'module' || exp.token.right === 'default') + // Since the `v0.10.0` version, it no longer matches whether there is an `exports.default` member, but exports directly. + // Because Vite will add `interop` related code snippets after the `import()` statement. + // `interop` snippets 👉 https://github.com/vitejs/vite/blob/v4.4.11/packages/vite/src/node/plugins/importAnalysis.ts#L874 + // Check needs interop 👉 https://github.com/vitejs/vite/blob/v4.4.11/packages/vite/src/node/optimizer/index.ts#L1165-L1166 + const memberDefault = { + declaration: 'const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports', + export: '__CJS__export_default__ as default', + } let members = analyzed.exports // Exclude `module.exports` and `exports.default` @@ -21,14 +26,14 @@ export function generateExport(analyzed: Analyzed): ExportsRuntime | null { // Remove duplicate export members = [...new Set(members)] - const membersDeclaration = members.map( - m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`, - ) - const membersExport = members.map(m => `__CJS__export_${m}__ as ${m}`) - if (memberDefault) { - membersDeclaration.unshift(`const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports`) - membersExport.unshift('__CJS__export_default__ as default') - } + const membersDeclaration = [ + memberDefault.declaration, + ...members.map(m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`), + ] + const membersExport = [ + memberDefault.export, + ...members.map(m => `__CJS__export_${m}__ as ${m}`), + ] return { polyfill: 'var module = { exports: {} }; var exports = module.exports;',