Skip to content

Commit

Permalink
feat: migrate optimizer to rollup
Browse files Browse the repository at this point in the history
  • Loading branch information
underfin committed Nov 7, 2023
1 parent 6516607 commit 5c5d0db
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions packages/vite/src/node/optimizer/esbuildDepPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import type { ImportKind, Plugin } from 'esbuild'
import type * as Rollup from 'rollup'
import { KNOWN_ASSET_TYPES } from '../constants'
import type { PackageCache } from '../packages'
import { getDepOptimizationConfig } from '../config'
Expand Down Expand Up @@ -332,3 +333,49 @@ export function esbuildCjsExternalPlugin(
},
}
}

// esbuild doesn't transpile `require('foo')` into `import` statements if 'foo' is externalized
// https://github.com/evanw/esbuild/issues/566#issuecomment-735551834
export function rollupCjsExternalPlugin(
externals: string[],
platform: 'node' | 'browser',
): Rollup.Plugin {
const filter = new RegExp(externals.map(matchesEntireLine).join('|'))

return {
name: 'cjs-external',
resolveId(id, importer, options) {
if (id.startsWith(nonFacadePrefix)) {
return {
id: id.slice(nonFacadePrefix.length),
external: true,
}
}

if (filter.test(id)) {
// TODO rolldown: kind is not available in rollup
const kind: ImportKind = options.custom?.kind
if (kind === 'require-call' && platform !== 'node') {
return {
id: cjsExternalFacadeNamespace + id,
}
}

return {
id,
external: true,
}
}
},
load(id) {
if (id.startsWith(cjsExternalFacadeNamespace)) {
return {
code:
`import * as m from ${JSON.stringify(
nonFacadePrefix + id.slice(cjsExternalFacadeNamespace.length),
)};` + `module.exports = m;`,
}
}
},
}
}

0 comments on commit 5c5d0db

Please sign in to comment.