Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: lazy load esbuild #15685

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { createRequire } from 'node:module'
import colors from 'picocolors'
import type { Alias, AliasOptions } from 'dep-types/alias'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import type { RollupOptions } from 'rollup'
import type { HookHandler, Plugin, PluginWithRequiredHook } from './plugin'
import type {
Expand All @@ -30,6 +29,7 @@ import {
asyncFlatten,
createDebugger,
createFilter,
importEsbuild,
isBuiltin,
isExternalUrl,
isFilePathESM,
Expand Down Expand Up @@ -1009,6 +1009,8 @@ async function bundleConfigFile(
const dirnameVarName = '__vite_injected_original_dirname'
const filenameVarName = '__vite_injected_original_filename'
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'

const { build } = await importEsbuild()
const result = await build({
absWorkingDir: process.cwd(),
entryPoints: [fileName],
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { promisify } from 'node:util'
import { performance } from 'node:perf_hooks'
import colors from 'picocolors'
import type { BuildContext, BuildOptions as EsbuildBuildOptions } from 'esbuild'
import esbuild, { build } from 'esbuild'
import { init, parse } from 'es-module-lexer'
import glob from 'fast-glob'
import { getDepOptimizationConfig } from '../config'
Expand All @@ -14,6 +13,7 @@ import {
createDebugger,
flattenId,
getHash,
importEsbuild,
isOptimizable,
isWindows,
lookupFile,
Expand Down Expand Up @@ -759,6 +759,7 @@ async function prepareEsbuildOptimizerRun(
}
plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr))

const esbuild = await importEsbuild()
const context = await esbuild.context({
absWorkingDir: process.cwd(),
entryPoints: Object.keys(flatIdDeps),
Expand Down Expand Up @@ -1058,6 +1059,7 @@ export async function extractExportsData(
// For custom supported extensions, build the entry file to transform it into JS,
// and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
// so only the entry file is being transformed.
const { build } = await importEsbuild()
const result = await build({
...esbuildOptions,
entryPoints: [filePath],
Expand Down
8 changes: 6 additions & 2 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type {
OnLoadResult,
Plugin,
} from 'esbuild'
import esbuild, { formatMessages, transform } from 'esbuild'
import colors from 'picocolors'
import type { ResolvedConfig } from '..'
import {
Expand All @@ -24,6 +23,7 @@ import {
createDebugger,
dataUrlRE,
externalRE,
importEsbuild,
isInNodeModules,
isObject,
isOptimizable,
Expand Down Expand Up @@ -135,6 +135,7 @@ export function scanImports(config: ResolvedConfig): {

`)
if (e.errors) {
const { formatMessages } = await importEsbuild()
const msgs = await formatMessages(e.errors, {
kind: 'error',
color: true,
Expand Down Expand Up @@ -216,7 +217,9 @@ async function prepareEsbuildScanner(
const { plugins = [], ...esbuildOptions } =
config.optimizeDeps?.esbuildOptions ?? {}

return await esbuild.context({
return await (
await importEsbuild()
).context({
absWorkingDir: process.cwd(),
write: false,
stdin: {
Expand Down Expand Up @@ -315,6 +318,7 @@ function esbuildScanPlugin(
let transpiledContents
// transpile because `transformGlobImport` only expects js
if (loader !== 'js') {
const { transform } = await importEsbuild()
transpiledContents = (await transform(contents, { loader })).code
} else {
transpiledContents = contents
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import type Less from 'less'
import type { Alias } from 'dep-types/alias'
import type { LightningCSSOptions } from 'dep-types/lightningcss'
import type { TransformOptions } from 'esbuild'
import { formatMessages, transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import { getCodeWithSourcemap, injectSourcesContent } from '../server/sourcemap'
import type { ModuleNode } from '../server/moduleGraph'
Expand Down Expand Up @@ -52,6 +51,7 @@ import {
generateCodeFrame,
getHash,
getPackageManagerCommand,
importEsbuild,
injectQuery,
isDataUrl,
isExternalUrl,
Expand Down Expand Up @@ -1723,6 +1723,8 @@ async function minifyCSS(
// LightningCSS output does not return a linebreak at the end
return code.toString() + (inlined ? '' : '\n')
}

const { formatMessages, transform } = await importEsbuild()
try {
const { code, warnings } = await transform(css, {
loader: 'css',
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { transform } from 'esbuild'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { escapeRegex, getHash } from '../utils'
import { escapeRegex, getHash, importEsbuild } from '../utils'
import { isCSSRequest } from './css'
import { isHTMLRequest } from './html'

Expand Down Expand Up @@ -148,6 +147,7 @@ export async function replaceDefine(

const esbuildOptions = config.esbuild || {}

const { transform } = await importEsbuild()
const result = await transform(code, {
loader: 'js',
charset: esbuildOptions.charset ?? 'utf8',
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import type {
TransformOptions,
TransformResult,
} from 'esbuild'
import { transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import type { InternalModuleFormat, SourceMap } from 'rollup'
import type { TSConfckParseResult } from 'tsconfck'
Expand All @@ -18,6 +17,7 @@ import {
createFilter,
ensureWatchedFile,
generateCodeFrame,
importEsbuild,
} from '../utils'
import type { ViteDevServer } from '../server'
import type { ResolvedConfig } from '../config'
Expand Down Expand Up @@ -173,6 +173,7 @@ export async function transformWithEsbuild(
delete resolvedOptions.jsxInject

try {
const { transform } = await importEsbuild()
const result = await transform(code, resolvedOptions)
let map: SourceMap
if (inMap && resolvedOptions.sourcemap) {
Expand Down
11 changes: 8 additions & 3 deletions packages/vite/src/node/publicUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
* Please control the side-effects by checking the ./dist/node-cjs/publicUtils.cjs bundle
*/
export { VERSION as version } from './constants'
export { version as esbuildVersion } from 'esbuild'
export { VERSION as rollupVersion } from 'rollup'
export {
splitVendorChunkPlugin,
splitVendorChunk,
isCSSRequest,
} from './plugins/splitVendorChunk'
export { normalizePath, mergeConfig, mergeAlias, createFilter } from './utils'
export {
normalizePath,
mergeConfig,
mergeAlias,
createFilter,
esbuildVersion,
rollupVersion,
} from './utils'
export { send } from './server/send'
export { createLogger } from './logger'
export { searchForWorkspaceRoot } from './server/searchRoot'
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/pluginContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ SOFTWARE.
import fs from 'node:fs'
import { join } from 'node:path'
import { performance } from 'node:perf_hooks'
import { VERSION as rollupVersion } from 'rollup'
import { parseAst as rollupParseAst } from 'rollup/parseAst'
import type {
AsyncPluginHooks,
Expand Down Expand Up @@ -74,6 +73,7 @@ import {
normalizePath,
numberToPos,
prettifyUrl,
rollupVersion,
timeFrom,
unwrapId,
} from '../utils'
Expand Down
31 changes: 31 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,26 @@ import {
} from './packages'
import type { CommonServerOptions } from '.'

// Cache lazy loaded esbuild import to avoid the extra cost of the import resolution on hot paths
// Only keep the functions we use to avoid keeping the promise and the entire module in memory
type EsbuildModule = typeof import('esbuild')
type EsbuildFunctions = Pick<
EsbuildModule,
'build' | 'transform' | 'context' | 'formatMessages'
>
let esbuildFunctions: EsbuildFunctions | Promise<EsbuildFunctions>
export async function importEsbuild(): Promise<EsbuildFunctions> {
if (esbuildFunctions) {
return esbuildFunctions
}
esbuildFunctions = import('esbuild').then((esbuild) => {
const { build, transform, context, formatMessages } = esbuild
esbuildFunctions = { build, transform, context, formatMessages }
return esbuildFunctions
})
return esbuildFunctions
}

/**
* Inlined to keep `@rollup/pluginutils` in devDependencies
*/
Expand Down Expand Up @@ -162,6 +182,17 @@ export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
// TODO: use import()
const _require = createRequire(import.meta.url)

export function resolveDependencyVersion(
dep: string,
pkgRelativePath = '../../package.json',
): string {
const pkgPath = path.resolve(_require.resolve(dep), pkgRelativePath)
return JSON.parse(fs.readFileSync(pkgPath, 'utf-8')).version
}

export const rollupVersion = resolveDependencyVersion('rollup')
export const esbuildVersion = resolveDependencyVersion('esbuild')

// set in bin/vite.js
const filter = process.env.VITE_DEBUG_FILTER

Expand Down