Skip to content

Commit

Permalink
feat: make esbuild optional peer dep (#78)
Browse files Browse the repository at this point in the history
* feat: use transformWithOxc for extractExportsData
* feat: make esbuild optional peer dep
* chore: fix types
  • Loading branch information
sapphi-red authored Dec 12, 2024
1 parent 7c66129 commit d97ef9e
Show file tree
Hide file tree
Showing 13 changed files with 87 additions and 61 deletions.
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export default tseslint.config(
{
allowModules: [
'vite',
'esbuild',
'less',
'sass',
'sass-embedded',
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@
},
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.24.0",
"lightningcss": "^1.28.1",
"postcss": "^8.4.49",
"rolldown": "0.15.0-snapshot-3cea4f5-20241211003613",
Expand Down Expand Up @@ -119,6 +118,7 @@
"dotenv": "^16.4.5",
"dotenv-expand": "^12.0.1",
"es-module-lexer": "^1.5.4",
"esbuild": "^0.24.0",
"escape-html": "^1.0.3",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
Expand Down Expand Up @@ -155,6 +155,7 @@
},
"peerDependencies": {
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"esbuild": "^0.24.0",
"jiti": ">=1.21.0",
"less": "*",
"lightningcss": "^1.21.0",
Expand All @@ -170,6 +171,9 @@
"@types/node": {
"optional": true
},
"esbuild": {
"optional": true
},
"jiti": {
"optional": true
},
Expand Down
11 changes: 3 additions & 8 deletions packages/vite/rollup.dts.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,11 @@ const identifierReplacements: Record<string, Record<string, string>> = {
Plugin$1: 'rolldown.Plugin',
PluginContext$1: 'rolldown.PluginContext',
TransformPluginContext$1: 'rolldown.TransformPluginContext',
TransformResult$3: 'rolldown.TransformResult',
TransformResult$2: 'rolldown.TransformResult',
},
'rolldown/experimental': {
TransformOptions$2: 'rolldown_experimental_TransformOptions',
TransformResult$2: 'rolldown_experimental_TransformResult',
},
esbuild: {
TransformResult$1: 'esbuild_TransformResult',
TransformOptions$1: 'esbuild_TransformOptions',
BuildOptions$1: 'esbuild_BuildOptions',
TransformOptions$1: 'rolldown_experimental_TransformOptions',
TransformResult$1: 'rolldown_experimental_TransformResult',
},
'node:https': {
Server$1: 'HttpsServer',
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
} from 'rolldown/experimental'
import type { RollupCommonJSOptions } from 'dep-types/commonjs'
import type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'
import type { TransformOptions } from 'esbuild'
import type { EsbuildTarget } from 'types/internal/esbuildOptions'
import type { ChunkMetadata } from 'types/metadata'
import { withTrailingSlash } from '../shared/utils'
import {
Expand Down Expand Up @@ -101,7 +101,7 @@ export interface BuildEnvironmentOptions {
* https://esbuild.github.io/content-types/#javascript for more details.
* @default 'modules'
*/
target?: 'modules' | TransformOptions['target'] | false
target?: 'modules' | EsbuildTarget | false
/**
* whether to inject module preload polyfill.
* Note: does not apply to library mode.
Expand Down Expand Up @@ -154,7 +154,7 @@ export interface BuildEnvironmentOptions {
* doesn't support the #RGBA syntax.
* @default target
*/
cssTarget?: TransformOptions['target'] | false
cssTarget?: EsbuildTarget | false
/**
* Override CSS minification specifically instead of defaulting to `build.minify`,
* so you can configure minification for JS and CSS separately.
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export type {
StylusPreprocessorOptions,
} from './plugins/css'
export type { JsonOptions } from './plugins/json'
export type { TransformOptions as EsbuildTransformOptions } from 'esbuild'
export type { EsbuildTransformOptions } from 'types/internal/esbuildOptions'
export type { ESBuildOptions, ESBuildTransformResult } from './plugins/esbuild'
export type { Manifest, ManifestChunk } from './plugins/manifest'
export type { ResolveOptions, InternalResolveOptions } from './plugins/resolve'
Expand Down
30 changes: 11 additions & 19 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import path from 'node:path'
import { promisify } from 'node:util'
import { performance } from 'node:perf_hooks'
import colors from 'picocolors'
import type { BuildOptions as EsbuildBuildOptions } from 'esbuild'
import { init, parse } from 'es-module-lexer'
import { isDynamicPattern } from 'tinyglobby'
import {
Expand All @@ -13,6 +12,7 @@ import {
type OutputOptions as RollupOutputOptions,
rolldown,
} from 'rolldown'
import type { DepsOptimizerEsbuildOptions } from 'types/internal/esbuildOptions'
import type { ResolvedConfig } from '../config'
import {
arraify,
Expand All @@ -28,10 +28,10 @@ import {
tryStatSync,
unique,
} from '../utils'
import { transformWithEsbuild } from '../plugins/esbuild'
import { METADATA_FILENAME } from '../constants'
import { isWindows } from '../../shared/utils'
import type { Environment } from '../environment'
import { transformWithOxc } from '../plugins/oxc'
import { ScanEnvironment, scanImports } from './scan'
import { createOptimizeDepsIncludeResolver, expandGlobIds } from './resolve'
import {
Expand Down Expand Up @@ -96,19 +96,7 @@ export interface DepOptimizationConfig {
*
* https://esbuild.github.io/api
*/
esbuildOptions?: Omit<
EsbuildBuildOptions,
| 'bundle'
| 'entryPoints'
| 'external'
| 'write'
| 'watch'
| 'outdir'
| 'outfile'
| 'outbase'
| 'outExtension'
| 'metafile'
>
esbuildOptions?: DepsOptimizerEsbuildOptions
rollupOptions?: Omit<RollupOptions, 'input' | 'logLevel' | 'output'> & {
output?: Omit<
RollupOutputOptions,
Expand Down Expand Up @@ -1100,14 +1088,18 @@ export async function extractExportsData(
try {
parseResult = parse(entryContent)
} catch {
const loader = rollupOptions.moduleTypes?.[path.extname(filePath)] || 'jsx'
const lang = rollupOptions.moduleTypes?.[path.extname(filePath)] || 'jsx'
debug?.(
`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`,
`Unable to parse: ${filePath}.\n Trying again with a ${lang} transform.`,
)
const transformed = await transformWithEsbuild(
if (lang !== 'jsx' && lang !== 'tsx' && lang !== 'ts') {
throw new Error(`Unable to parse : ${filePath}.`)
}
const transformed = await transformWithOxc(
undefined,
entryContent,
filePath,
{ loader },
{ lang },
undefined,
environment.config,
)
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import fs from 'node:fs'
import fsp from 'node:fs/promises'
import path from 'node:path'
import { performance } from 'node:perf_hooks'
import type { Loader } from 'esbuild'
import { scan, transform } from 'rolldown/experimental'
import type { PartialResolvedId, Plugin } from 'rolldown'
import colors from 'picocolors'
Expand Down Expand Up @@ -335,6 +334,8 @@ function globEntries(pattern: string | string[], environment: ScanEnvironment) {
})
}

type Loader = 'js' | 'ts' | 'jsx' | 'tsx'

export const scriptRE =
/(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis
export const commentRE = /<!--.*?-->/gs
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import type Stylus from 'stylus'
import type Less from 'less'
import type { Alias } from 'dep-types/alias'
import type { LightningCSSOptions } from 'types/internal/lightningcssOptions'
import type { TransformOptions } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import { WorkerWithFallback } from 'artichokie'
import { globSync } from 'tinyglobby'
Expand All @@ -37,6 +36,7 @@ import type {
TransformAttributeResult as LightningCssTransformAttributeResult,
TransformResult as LightningCssTransformResult,
} from 'lightningcss'
import type { EsbuildTransformOptions } from 'types/internal/esbuildOptions'
import { getCodeWithSourcemap, injectSourcesContent } from '../server/sourcemap'
import type { EnvironmentModuleNode } from '../server/moduleGraph'
import {
Expand Down Expand Up @@ -1989,8 +1989,8 @@ async function minifyCSS(

function resolveMinifyCssEsbuildOptions(
options: ESBuildOptions,
): TransformOptions {
const base: TransformOptions = {
): EsbuildTransformOptions {
const base: EsbuildTransformOptions = {
charset: options.charset ?? 'utf8',
logLevel: options.logLevel,
logLimit: options.logLimit,
Expand Down
42 changes: 24 additions & 18 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import path from 'node:path'
import colors from 'picocolors'
import type {
Loader,
Message,
TransformOptions,
TransformResult,
} from 'esbuild'
import { transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import type { InternalModuleFormat, SourceMap } from 'rolldown'
import type { TSConfckParseResult } from 'tsconfck'
import { TSConfckCache, TSConfckParseError, parse } from 'tsconfck'
import type { FSWatcher } from 'dep-types/chokidar'
import type {
EsbuildLoader,
EsbuildMessage,
EsbuildTransformOptions,
EsbuildTransformResult as RawEsbuildTransformResult,
} from 'types/internal/esbuildOptions'
import {
combineSourcemaps,
createDebugger,
Expand Down Expand Up @@ -42,7 +41,7 @@ export const defaultEsbuildSupported = {
'import-meta': true,
}

export interface ESBuildOptions extends TransformOptions {
export interface ESBuildOptions extends EsbuildTransformOptions {
include?: string | RegExp | string[] | RegExp[]
exclude?: string | RegExp | string[] | RegExp[]
jsxInject?: string
Expand All @@ -52,7 +51,7 @@ export interface ESBuildOptions extends TransformOptions {
minify?: never
}

export type ESBuildTransformResult = Omit<TransformResult, 'map'> & {
export type ESBuildTransformResult = Omit<RawEsbuildTransformResult, 'map'> & {
map: SourceMap
}

Expand All @@ -75,10 +74,16 @@ type TSConfigJSON = {
}
type TSCompilerOptions = NonNullable<TSConfigJSON['compilerOptions']>

let esbuild: Promise<typeof import('esbuild')> | undefined
const importEsbuild = () => {
esbuild ||= import('esbuild')
return esbuild
}

export async function transformWithEsbuild(
code: string,
filename: string,
options?: TransformOptions,
options?: EsbuildTransformOptions,
inMap?: object,
config?: ResolvedConfig,
watcher?: FSWatcher,
Expand All @@ -97,7 +102,7 @@ export async function transformWithEsbuild(
} else if (ext === 'cts' || ext === 'mts') {
loader = 'ts'
} else {
loader = ext as Loader
loader = ext as EsbuildLoader
}
}

Expand Down Expand Up @@ -178,7 +183,7 @@ export async function transformWithEsbuild(
}
}

const resolvedOptions: TransformOptions = {
const resolvedOptions: EsbuildTransformOptions = {
sourcemap: true,
// ensure source file name contains full query
sourcefile: filename,
Expand All @@ -197,6 +202,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 All @@ -221,7 +227,7 @@ export async function transformWithEsbuild(
// patch error information
if (e.errors) {
e.frame = ''
e.errors.forEach((m: Message) => {
e.errors.forEach((m: EsbuildMessage) => {
if (
m.text === 'Experimental decorators are not currently enabled' ||
m.text ===
Expand All @@ -246,7 +252,7 @@ export function esbuildPlugin(config: ResolvedConfig): Plugin {

// Remove optimization options for dev as we only need to transpile them,
// and for build as the final optimization is in `buildEsbuildPlugin`
const transformOptions: TransformOptions = {
const transformOptions: EsbuildTransformOptions = {
target: 'esnext',
charset: 'utf8',
...esbuildTransformOptions,
Expand Down Expand Up @@ -301,7 +307,7 @@ export function esbuildPlugin(config: ResolvedConfig): Plugin {

const rollupToEsbuildFormatMap: Record<
string,
TransformOptions['format'] | undefined
EsbuildTransformOptions['format'] | undefined
> = {
es: 'esm',
cjs: 'cjs',
Expand Down Expand Up @@ -375,7 +381,7 @@ export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => {
export function resolveEsbuildTranspileOptions(
config: ResolvedConfig,
format: InternalModuleFormat,
): TransformOptions | null {
): EsbuildTransformOptions | null {
const target = config.build.target
const minify = config.build.minify === 'esbuild'

Expand All @@ -389,7 +395,7 @@ export function resolveEsbuildTranspileOptions(
const isEsLibBuild = config.build.lib && format === 'es'
const esbuildOptions = config.esbuild || {}

const options: TransformOptions = {
const options: EsbuildTransformOptions = {
charset: 'utf8',
...esbuildOptions,
loader: 'js',
Expand Down Expand Up @@ -461,7 +467,7 @@ export function resolveEsbuildTranspileOptions(
}
}

function prettifyMessage(m: Message, code: string): string {
function prettifyMessage(m: EsbuildMessage, code: string): string {
let res = colors.yellow(m.text)
if (m.location) {
res += `\n` + generateCodeFrame(code, m.location)
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/oxc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface OxcOptions extends OxcTransformOptions {
}

export async function transformWithOxc(
ctx: PluginContext,
ctx: PluginContext | undefined,
code: string,
filename: string,
options?: OxcTransformOptions,
Expand Down Expand Up @@ -110,7 +110,7 @@ export async function transformWithOxc(
break
case 'preserve':
if (lang === 'tsx') {
ctx.warn('The tsconfig jsx preserve is not supported by oxc')
ctx?.warn('The tsconfig jsx preserve is not supported by oxc')
}
break
default:
Expand Down Expand Up @@ -151,7 +151,7 @@ export async function transformWithOxc(
resolvedOptions.typescript ??= {}
resolvedOptions.typescript.onlyRemoveTypeImports = false
} else {
ctx.warn(
ctx?.warn(
`preserveValueImports=${preserveValueImports} + importsNotUsedAsValues=${importsNotUsedAsValues} is not supported by oxc.` +
'Please migrate to the new verbatimModuleSyntax option.',
)
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/node/publicUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export {
DEFAULT_SERVER_CONDITIONS as defaultServerConditions,
DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields,
} from './constants'
export { version as esbuildVersion } from 'esbuild'
export {
splitVendorChunkPlugin,
splitVendorChunk,
Expand Down
Loading

0 comments on commit d97ef9e

Please sign in to comment.