diff --git a/packages/commonjs/README.md b/packages/commonjs/README.md index 53afe5217..f955e578b 100644 --- a/packages/commonjs/README.md +++ b/packages/commonjs/README.md @@ -63,6 +63,13 @@ You can also provide a [picomatch pattern](https://github.com/micromatch/picomat `"debug"` works like `"auto"` but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as picomatch pattern for fine-tuning or to avoid the potential race conditions mentioned for `"auto"`. +### `namedExportsForEntries` + +Type: `boolean`
+Default: `false` + +Set this to `true` to expose named exports when bundling a wrapped CommonJS module as an entry point. For example, `exports.Client = Client` or `module.exports.Client = Client` makes `Client` available as a named import from the generated bundle. Named exports snapshot own data properties when the entry finishes executing. Use the CommonJS exports object for computed names, getters, and later changes. The plugin omits names it sees defined as accessors. If a property becomes an accessor indirectly, its named export is `undefined` and its getter remains lazy. + ### `requireNodeBuiltins` Type: `boolean`
diff --git a/packages/commonjs/src/ast-utils.js b/packages/commonjs/src/ast-utils.js index b32686fbf..5cf9d7f27 100644 --- a/packages/commonjs/src/ast-utils.js +++ b/packages/commonjs/src/ast-utils.js @@ -74,53 +74,24 @@ export function getKeypath(node) { export const KEY_COMPILED_ESM = '__esModule'; -export function getDefineCompiledEsmType(node) { - const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports'); - const definedProperty = - definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports'); - if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { - return isTruthy(definedProperty.value) - ? definedPropertyWithExports - ? 'exports' - : 'module' - : false; +export function getDefinedExport(node) { + if (node.arguments.length !== 3 || getKeypath(node.callee)?.keypath !== 'Object.defineProperty') { + return null; } - return false; -} - -function getDefinePropertyCallName(node, targetName) { - const { - callee: { object, property } - } = node; - if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; - if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; - if (node.arguments.length !== 3) return; - - const targetNames = targetName.split('.'); - const [target, key, value] = node.arguments; - if (targetNames.length === 1) { - if (target.type !== 'Identifier' || target.name !== targetNames[0]) { - return; - } + const [target, propertyName, descriptor] = node.arguments; + const targetPath = getKeypath(target); + if ( + (targetPath?.keypath !== 'exports' && targetPath?.keypath !== 'module.exports') || + descriptor.type !== 'ObjectExpression' || + typeof propertyName.value !== 'string' + ) { + return null; } - - if (targetNames.length === 2) { - if ( - target.type !== 'MemberExpression' || - target.object.name !== targetNames[0] || - target.property.name !== targetNames[1] - ) { - return; - } - } - - if (value.type !== 'ObjectExpression' || !value.properties) return; - - const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); - if (!valueProperty || !valueProperty.value) return; - - // eslint-disable-next-line consistent-return - return { key: key.value, value: valueProperty.value }; + const value = descriptor.properties.find((property) => property.key?.name === 'value'); + const isAccessor = descriptor.properties.some(({ key, computed }) => + ['get', 'set'].includes(computed ? key?.value : key?.name ?? key?.value) + ); + return { name: propertyName.value, target: targetPath.name, value: value?.value, isAccessor }; } export function isShorthandProperty(parent) { diff --git a/packages/commonjs/src/index.js b/packages/commonjs/src/index.js index 6476ab423..0fccfa805 100644 --- a/packages/commonjs/src/index.js +++ b/packages/commonjs/src/index.js @@ -276,16 +276,12 @@ export default function commonjs(options = {}) { // entry suffix is just appended to not mess up relative external resolution if (id.endsWith(ENTRY_SUFFIX)) { - const acutalId = id.slice(0, -ENTRY_SUFFIX.length); - const { - meta: { commonjs: commonjsMeta } - } = this.getModuleInfo(acutalId); - const shebang = commonjsMeta?.shebang ?? ''; + const actualId = id.slice(0, -ENTRY_SUFFIX.length); return getEntryProxy( - acutalId, - getDefaultIsModuleExports(acutalId), - this.getModuleInfo, - shebang + actualId, + getDefaultIsModuleExports(actualId), + this.getModuleInfo(actualId), + options.namedExportsForEntries ); } diff --git a/packages/commonjs/src/proxies.js b/packages/commonjs/src/proxies.js index 72aae3640..d3825d106 100644 --- a/packages/commonjs/src/proxies.js +++ b/packages/commonjs/src/proxies.js @@ -1,4 +1,4 @@ -import { HELPERS_ID, IS_WRAPPED_COMMONJS } from './helpers'; +import { ES_IMPORT_SUFFIX, HELPERS_ID, IS_WRAPPED_COMMONJS, wrapId } from './helpers'; import { capitalize, getName } from './utils'; export function getUnknownRequireProxy(id, requireReturnsDefault) { @@ -44,24 +44,36 @@ export async function getStaticRequireProxy(id, requireReturnsDefault, loadModul return `export { default } from ${JSON.stringify(id)};`; } -export function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) { - const { - meta: { commonjs: commonjsMeta }, - hasDefaultExport - } = getModuleInfo(id); - if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { - const stringifiedId = JSON.stringify(id); - let code = `export * from ${stringifiedId};`; - if (hasDefaultExport) { - code += `export { default } from ${stringifiedId};`; +export function getEntryProxy(id, defaultIsModuleExports, moduleInfo, namedExportsForEntries) { + const { commonjs } = moduleInfo.meta; + const shebang = commonjs?.shebang ?? ''; + const usesRequireWrapper = commonjs?.isCommonJS === IS_WRAPPED_COMMONJS; + const names = (namedExportsForEntries && commonjs?.entryExportNames) || []; + if (usesRequireWrapper && !names.length) { + const result = getEsImportProxy(id, defaultIsModuleExports, true); + return { ...result, code: shebang + result.code }; + } + + // A wrapped module exposes its exports object through the ES import proxy. + const source = JSON.stringify(usesRequireWrapper ? wrapId(id, ES_IMPORT_SUFFIX) : id); + let code = `${shebang}export * from ${source};`; + if (usesRequireWrapper || moduleInfo.hasDefaultExport) { + code += `export { default } from ${source};`; + } + if (names.length) { + code += ` +import { __moduleExports as entry } from ${source}; +function getEntryExport(name) { + var descriptor = entry == null ? undefined : Object.getOwnPropertyDescriptor(entry, name); + return descriptor && descriptor.value; +}`; + for (const name of names) { + code += ` +var named_${name} = /*@__PURE__*/getEntryExport(${JSON.stringify(name)}); +export { named_${name} as ${name} };`; } - return shebang + code; } - const result = getEsImportProxy(id, defaultIsModuleExports, true); - return { - ...result, - code: shebang + result.code - }; + return code; } export function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) { diff --git a/packages/commonjs/src/resolve-require-sources.js b/packages/commonjs/src/resolve-require-sources.js index 8f81cb820..5881a6846 100644 --- a/packages/commonjs/src/resolve-require-sources.js +++ b/packages/commonjs/src/resolve-require-sources.js @@ -144,13 +144,13 @@ export function getRequireResolver( .filter(({ id, external }) => !(external || parentRequireSet.has(id))) .map(async (resolved) => { if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { + const { meta } = await this.load(resolved); + // An entry proxy imports the ES import proxy by its already resolved ID. + const importee = meta.commonjs?.resolved ?? { + id: unwrapId(resolved.id, ES_IMPORT_SUFFIX) + }; return ( - (await getTypeForImportedModule( - ( - await this.load(resolved) - ).meta.commonjs.resolved, - this.load - )) !== IS_WRAPPED_COMMONJS + (await getTypeForImportedModule(importee, this.load)) !== IS_WRAPPED_COMMONJS ); } return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; diff --git a/packages/commonjs/src/transform-commonjs.js b/packages/commonjs/src/transform-commonjs.js index 2bc22ae88..5ed67cbc5 100644 --- a/packages/commonjs/src/transform-commonjs.js +++ b/packages/commonjs/src/transform-commonjs.js @@ -8,7 +8,7 @@ import MagicString from 'magic-string'; import { getKeypath, - getDefineCompiledEsmType, + getDefinedExport, isFalsy, isReference, isShorthandProperty, @@ -100,6 +100,7 @@ export default async function transformCommonjs( const moduleExportsAssignments = []; let firstTopLevelModuleExportsAssignment = null; const exportsAssignmentsByName = new Map(); + const accessorExports = new Set(); const topLevelAssignments = new Set(); const topLevelDefineCompiledEsmExpressions = []; const replacedGlobal = []; @@ -184,7 +185,18 @@ export default async function transformCommonjs( } return; case 'CallExpression': { - const defineCompiledEsmType = getDefineCompiledEsmType(node); + const definedExport = getDefinedExport(node); + if ( + definedExport?.isAccessor && + !scope.contains('Object') && + !scope.contains(definedExport.target) + ) { + accessorExports.add(definedExport.name); + } + const defineCompiledEsmType = + definedExport?.name === KEY_COMPILED_ESM && + isTruthy(definedExport.value) && + definedExport.target; if (defineCompiledEsmType) { if (programDepth === 3 && parent.type === 'ExpressionStatement') { // skip special handling for [module.]exports until we know we render this @@ -592,6 +604,18 @@ function ${requireName} () { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', - meta: { commonjs: { ...commonjsMeta, shebang } } + meta: { + commonjs: { + ...commonjsMeta, + shebang, + entryExportNames: + usesRequireWrapper || shouldWrap + ? [...exportsAssignmentsByName.keys()].filter( + (name) => + name !== 'default' && name !== '__moduleExports' && !accessorExports.has(name) + ) + : null + } + } }; } diff --git a/packages/commonjs/test/test.js b/packages/commonjs/test/test.js index dcf3b3c72..ddc0526e9 100644 --- a/packages/commonjs/test/test.js +++ b/packages/commonjs/test/test.js @@ -294,6 +294,107 @@ test('import CommonJS module with esm property should get default export ', asyn const result2 = await executeBundle(bundle2, avaAssertions); expect(result2.error.message).toBe('libExports is not a function'); }); +test.each([ + { strictRequires: true, namedExportsForEntries: true }, + { strictRequires: false, namedExportsForEntries: true }, + { strictRequires: true, namedExportsForEntries: false }, + { strictRequires: false, namedExportsForEntries: false } +])('wrapped entry exports with %o', async ({ strictRequires, namedExportsForEntries }) => { + const bundle = await rollup({ + input: 'main.js', + plugins: [ + loader({ + 'main.js': ` + globalThis.calls = (globalThis.calls || 0) + 1; + exports.default = 42; + exports.class = 'reserved'; + module.exports.answer = globalThis.calls; + module.exports.answer += 1; + module.exports['dynamic' + globalThis.calls] = 123; + ` + }), + commonjs({ strictRequires, namedExportsForEntries }) + ] + }); + const { + output: [chunk] + } = await bundle.generate({ format: 'es' }); + expect(chunk.exports).toEqual( + namedExportsForEntries ? ['answer', 'class', 'default'] : ['default'] + ); + const { exports, global } = await executeBundle(bundle, avaAssertions, { exports: 'named' }); + expect(global.calls).toBe(1); + expect(exports.default).toEqual({ answer: 2, class: 'reserved', default: 42, dynamic1: 123 }); + if (namedExportsForEntries) { + expect(exports.answer).toBe(exports.default.answer); + expect(exports.class).toBe('reserved'); + } +}); + +test('rebuilds wrapped entries with named exports from the Rollup cache', async () => { + const modules = { 'main.js': 'exports.answer = 42;' }; + const options = { + input: 'main.js', + plugins: [loader(modules), commonjs({ namedExportsForEntries: true })] + }; + let bundle = await rollup(options); + const code = await getCodeFromBundle(bundle, { format: 'es' }); + + bundle = await rollup({ ...options, cache: bundle.cache }); + expect(await getCodeFromBundle(bundle, { format: 'es' })).toBe(code); + + modules['main.js'] = 'exports.updated = 43;'; + bundle = await rollup({ ...options, cache: bundle.cache }); + const { exports } = await executeBundle(bundle, avaAssertions, { exports: 'named' }); + expect(exports).toEqual({ default: { updated: 43 }, updated: 43 }); +}); + +test('keeps accessor exports lazy and excludes computed names from the entry facade', async () => { + const bundle = await rollup({ + input: 'main.js', + plugins: [ + loader({ + 'main.js': ` + exports.lazy = undefined; + Object.defineProperty(exports, 'lazy', { get() { throw new Error('lazy getter'); } }); + exports.indirect = 0; + const key = 'indirect'; + Object.defineProperty(module.exports, key, { get() { throw new Error('indirect getter'); } }); + exports.data = 1; + Object.defineProperty(exports, 'data', { value: 2 }); + exports['not-an-identifier'] = 3; + ` + }), + commonjs({ namedExportsForEntries: true }) + ] + }); + const { + output: [chunk] + } = await bundle.generate({ format: 'es' }); + expect(chunk.exports).toEqual(['data', 'default', 'indirect']); + const result = await executeBundle(bundle, avaAssertions, { exports: 'named' }); + expect(result.error).toBeUndefined(); + expect(result.exports.data).toBe(2); + expect(result.exports.indirect).toBeUndefined(); + expect(result.exports.default['not-an-identifier']).toBe(3); + expect(() => result.exports.default.lazy).toThrow('lazy getter'); + expect(() => result.exports.default.indirect).toThrow('indirect getter'); +}); + +test('allows wrapped entries to replace their exports after assigning properties', async () => { + const bundle = await rollup({ + input: 'main.js', + plugins: [ + loader({ 'main.js': 'exports.toString = () => "initial"; module.exports = null;' }), + commonjs({ namedExportsForEntries: true }) + ] + }); + const result = await executeBundle(bundle, avaAssertions, { exports: 'named' }); + expect(result.error).toBeUndefined(); + expect(result.exports.default).toBe(null); + expect(result.exports.toString).toBeUndefined(); +}); + test('identifies named exports from object literals', async () => { const bundle = await rollup({ input: 'fixtures/samples/named-exports-from-object-literal/main.js', diff --git a/packages/commonjs/test/types.ts b/packages/commonjs/test/types.ts index 67439d3cf..e505588bc 100644 --- a/packages/commonjs/test/types.ts +++ b/packages/commonjs/test/types.ts @@ -22,7 +22,8 @@ const config: RollupOptions = { ignore: ['conditional-runtime-dependency'], dynamicRequireTargets: ['node_modules/logform/*.js'], dynamicRequireRoot: 'node_modules', - strictRequires: ['node_modules/foo/*.js'] + strictRequires: ['node_modules/foo/*.js'], + namedExportsForEntries: true }) ] }; diff --git a/packages/commonjs/types/index.d.ts b/packages/commonjs/types/index.d.ts index 2d6ad2004..89598480f 100644 --- a/packages/commonjs/types/index.d.ts +++ b/packages/commonjs/types/index.d.ts @@ -98,6 +98,12 @@ interface RollupCommonJSOptions { * @default "auto" */ strictRequires?: boolean | FilterPattern; + /** + * Expose statically detected property assignments as named exports of wrapped + * CommonJS entry points in the generated bundle. + * @default false + */ + namedExportsForEntries?: boolean; /** * Sometimes you have to leave require statements unconverted. Pass an array * containing the IDs or a `id => boolean` function.