diff --git a/scripts/build.js b/scripts/build.js index 0dc11ce06b..873706f2ed 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -304,6 +304,25 @@ const lazyGrammarPlugin = { }, }; +/** + * Makes `require("prismjs")` return the default export directly with named + * exports as properties, so CJS consumers don't need `.default`. + * + * @type {Plugin} + */ +const cjsExportPlugin = { + name: 'cjs-default-export', + renderChunk (code) { + if (!code.includes('exports.default=')) { + return null; + } + + code += 'module.exports=Object.assign(exports.default,exports);'; + + return { code, map: null }; + }, +}; + /** * @param {MagicString} s * @returns {{ code: string; map: SourceMapInput }} @@ -411,16 +430,20 @@ async function buildJS () { const bundles = { esm: { rollupOptions: defaultRollupOptions, - outputOptions: defaultOutputOptions, + outputOptions: { + ...defaultOutputOptions, + format: 'es', + }, }, cjs: { rollupOptions: { ...defaultRollupOptions, - plugins: [...defaultRollupOptions.plugins, commonjs()], + plugins: [...defaultRollupOptions.plugins, commonjs(), cjsExportPlugin], }, outputOptions: { ...defaultOutputOptions, dir: './dist/cjs', + format: 'cjs', }, }, }; @@ -430,6 +453,14 @@ async function buildJS () { bundle.build = await rollup(bundle.rollupOptions); await bundle.build.write(bundle.outputOptions); } + // The root package.json has "type": "module", so Node treats all .js files as ESM. + // This overrides that for the CJS directory, since Node uses the nearest parent + // package.json to determine the module system: https://nodejs.org/api/packages.html#type + await writeFile( + path.join(DIST_DIR, 'cjs', 'package.json'), + JSON.stringify({ type: 'commonjs' }), + 'utf-8' + ); } finally { for (const bundle of Object.values(bundles)) {