Skip to content

Commit c9fce24

Browse files
committedAug 10, 2022
feat(rollup): generated named exports in esm stub
1 parent b87c8df commit c9fce24

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed
 

‎src/builder/rollup.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import _esbuild from 'rollup-plugin-esbuild'
1010
import dts from 'rollup-plugin-dts'
1111
import replace from '@rollup/plugin-replace'
1212
import { relative, resolve, dirname } from 'pathe'
13-
import { resolvePath } from 'mlly'
13+
import { resolvePath, resolveModuleExportNames } from 'mlly'
1414
import { getpkg, tryResolve, warn } from '../utils'
1515
import type { BuildContext } from '../types'
1616
import { JSONPlugin } from './plugins/json'
@@ -33,12 +33,19 @@ export async function rollupBuild (ctx: BuildContext) {
3333
const shebang = getShebang(code)
3434

3535
await mkdir(dirname(output), { recursive: true })
36+
37+
// CJS Stub
3638
if (ctx.options.rollup.emitCJS) {
37-
await writeFile(output + '.cjs', `${shebang}module.exports = require(${JSON.stringify(jitiPath)})(null, { interopDefault: true, esmResolve: true })('${entry.input}')`)
39+
await writeFile(output + '.cjs', `${shebang}module.exports = require(${JSON.stringify(jitiPath)})(null, { interopDefault: true, esmResolve: true })('${resolvedEntry}')`)
3840
}
39-
// Use file:// protocol for windows compatibility
40-
await writeFile(output + '.mjs', `${shebang}import jiti from ${JSON.stringify(pathToFileURL(jitiPath).href)};\nexport default jiti(null, { interopDefault: true, esmResolve: true })('${entry.input}');`)
41-
await writeFile(output + '.d.ts', `export * from '${entry.input}';\nexport { default } from '${entry.input}';`)
41+
42+
// MJS Stub
43+
// Try to analyze exports
44+
const namedExports = await resolveModuleExportNames(resolvedEntry)
45+
await writeFile(output + '.mjs', `${shebang}import jiti from ${JSON.stringify(pathToFileURL(jitiPath).href)};\nconst _module = jiti(null, { interopDefault: true, esmResolve: true })('${resolvedEntry}');\n\nexport default _module;\n\n${namedExports.map(name => `export const ${name} = _module.${name};`).join('\n')}`)
46+
47+
// DTS Stub
48+
await writeFile(output + '.d.ts', `export * from '${entry.input}';\nexport { default } from '${resolvedEntry}';`)
4249

4350
if (shebang) {
4451
await makeExecutable(output + '.cjs')

0 commit comments

Comments
 (0)
Please sign in to comment.