diff --git a/packages/markdown-exit/src/index.core.ts b/packages/markdown-exit/src/index.core.ts index 8cef5ae..7c1b613 100644 --- a/packages/markdown-exit/src/index.core.ts +++ b/packages/markdown-exit/src/index.core.ts @@ -11,7 +11,9 @@ export * from './token' // for correct d.ts generation type MarkdownExitConstructor = InstanceType +// Marked pure so bundlers can drop `MarkdownExit` with its renderer and presets +// when an app imports only `Parser` or other parser exports. // eslint-disable-next-line ts/no-redeclare -const MarkdownExitConstructor = callable(MarkdownExit) as unknown as (typeof createMarkdownExit & typeof MarkdownExit) +const MarkdownExitConstructor = /* @__PURE__ */ callable(MarkdownExit) as unknown as (typeof createMarkdownExit & typeof MarkdownExit) export default MarkdownExitConstructor diff --git a/packages/markdown-exit/tests/core-entry.test.ts b/packages/markdown-exit/tests/core-entry.test.ts index 91aef68..f6ad95f 100644 --- a/packages/markdown-exit/tests/core-entry.test.ts +++ b/packages/markdown-exit/tests/core-entry.test.ts @@ -18,12 +18,47 @@ async function bundleImports(entry: string): Promise { return result[0].output.flatMap(chunk => chunk.type === 'chunk' ? chunk.imports : []) } +const ENTRY = 'virtual:entry' + +// Maps each bundled module id to the length of its code left after tree-shaking. +async function bundleRenderedLengths(code: string): Promise> { + const result = await build({ + configFile: false, + logLevel: 'silent', + plugins: [{ + name: 'virtual-entry', + resolveId: id => id === ENTRY ? id : null, + load: id => id === ENTRY ? code : null, + }], + build: { + write: false, + minify: false, + rollupOptions: { + input: ENTRY, + external: id => id !== ENTRY && !id.startsWith('.') && !id.startsWith('/'), + }, + }, + }) as Rollup.RollupOutput | Rollup.RollupOutput[] + const chunks = [result].flat()[0].output.filter(chunk => chunk.type === 'chunk') + return new Map(chunks.flatMap(chunk => Object.entries(chunk.modules).map(([id, module]) => [id, module.renderedLength]))) +} + describe('markdown-exit/core', () => { it('does not bundle linkify-it', async () => { assert.include(await bundleImports('../src/index.ts'), 'linkify-it') assert.notInclude(await bundleImports('../src/index.core.ts'), 'linkify-it') }) + it('tree-shakes the renderer and presets when only `Parser` is imported', async () => { + const core = fileURLToPath(new URL('../src/index.core.ts', import.meta.url)) + const lengths = await bundleRenderedLengths(`import { Parser } from ${JSON.stringify(core)}\nconsole.log(new Parser().parse('# a'))`) + const rendered = (path: string) => [...lengths].reduce((sum, [id, length]) => id.includes(path) ? sum + length : sum, 0) + + assert.isAbove(rendered('/src/parser/parser.ts'), 0) + assert.strictEqual(rendered('/src/renderer.ts'), 0) + assert.strictEqual(rendered('/src/presets/'), 0) + }) + it('renders without linkify-it', () => { const md = MarkdownExit()