Skip to content

Commit

Permalink
refactor: upgrade to esbuild 0.9.x (#2506)
Browse files Browse the repository at this point in the history
  • Loading branch information
egoist authored Mar 15, 2021
1 parent b18af15 commit d3142cf
Show file tree
Hide file tree
Showing 7 changed files with 20 additions and 56 deletions.
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
"//": "READ .github/contributing.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.8.52",
"esbuild": "^0.9.2",
"postcss": "^8.2.1",
"resolve": "^1.19.0",
"rollup": "^2.38.5"
Expand Down
4 changes: 1 addition & 3 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from './utils'
import { resolvePlugins } from './plugins'
import chalk from 'chalk'
import { ESBuildOptions, esbuildPlugin, stopService } from './plugins/esbuild'
import { ESBuildOptions, esbuildPlugin } from './plugins/esbuild'
import dotenv from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import { Alias, AliasOptions } from 'types/alias'
Expand Down Expand Up @@ -718,8 +718,6 @@ export async function loadConfigFromFile(
chalk.red(`failed to load config from ${resolvedPath}`)
)
throw e
} finally {
await stopService()
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/optimizer/esbuildDepPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path'
import { Loader, Plugin, ResolveKind } from 'esbuild'
import { Loader, Plugin, ImportKind } from 'esbuild'
import { KNOWN_ASSET_TYPES } from '../constants'
import { ResolvedConfig } from '..'
import {
Expand Down Expand Up @@ -47,7 +47,7 @@ export function esbuildDepPlugin(
const resolve = (
id: string,
importer: string,
kind: ResolveKind,
kind: ImportKind,
resolveDir?: string
): Promise<string | undefined> => {
let _importer
Expand Down
15 changes: 5 additions & 10 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { createHash } from 'crypto'
import { build } from 'esbuild'
import { ResolvedConfig } from '../config'
import {
createDebugger,
Expand All @@ -14,7 +15,6 @@ import {
import { esbuildDepPlugin } from './esbuildDepPlugin'
import { ImportSpecifier, init, parse } from 'es-module-lexer'
import { scanImports } from './scan'
import { ensureService, stopService } from '../plugins/esbuild'

const debug = createDebugger('vite:deps')

Expand Down Expand Up @@ -191,8 +191,6 @@ export async function optimizeDeps(
logger.info(chalk.greenBright(`Optimizing dependencies:\n ${depsString}`))
}

const esbuildMetaPath = path.join(cacheDir, '_esbuild.json')

// esbuild generates nested directory output with lowest common ancestor base
// this is unpredictable and makes it difficult to analyze entry / output
// mapping. So what we do here is:
Expand Down Expand Up @@ -227,8 +225,8 @@ export async function optimizeDeps(
}

const start = Date.now()
const esbuildService = await ensureService()
await esbuildService.build({

const result = await build({
entryPoints: Object.keys(flatIdDeps),
bundle: true,
keepNames: true,
Expand All @@ -239,12 +237,12 @@ export async function optimizeDeps(
sourcemap: true,
outdir: cacheDir,
treeShaking: 'ignore-annotations',
metafile: esbuildMetaPath,
metafile: true,
define,
plugins: [esbuildDepPlugin(flatIdDeps, flatIdToExports, config)]
})

const meta = JSON.parse(fs.readFileSync(esbuildMetaPath, 'utf-8'))
const meta = result.metafile!

for (const id in deps) {
const entry = deps[id]
Expand All @@ -256,9 +254,6 @@ export async function optimizeDeps(
}

writeFile(dataPath, JSON.stringify(data, null, 2))
if (asCommand) {
await stopService()
}

debug(`deps bundled in ${Date.now() - start}ms`)
return data
Expand Down
8 changes: 3 additions & 5 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs'
import path from 'path'
import glob from 'fast-glob'
import { ResolvedConfig } from '..'
import { Loader, Plugin } from 'esbuild'
import { Loader, Plugin, build, transform } from 'esbuild'
import {
KNOWN_ASSET_TYPES,
JS_TYPES_RE,
Expand All @@ -25,7 +25,6 @@ import {
import { init, parse } from 'es-module-lexer'
import MagicString from 'magic-string'
import { transformImportGlob } from '../importGlob'
import { ensureService } from '../plugins/esbuild'

const debug = createDebugger('vite:deps')

Expand Down Expand Up @@ -82,10 +81,9 @@ export async function scanImports(
const container = await createPluginContainer(config)
const plugin = esbuildScanPlugin(config, container, deps, missing, entries)

const esbuildService = await ensureService()
await Promise.all(
entries.map((entry) =>
esbuildService.build({
build({
entryPoints: [entry],
bundle: true,
format: 'esm',
Expand Down Expand Up @@ -362,7 +360,7 @@ async function transformGlob(
) {
// transform the content first since es-module-lexer can't handle non-js
if (loader !== 'js') {
source = (await (await ensureService()).transform(source, { loader })).code
source = (await transform(source, { loader })).code
}

await init
Expand Down
35 changes: 4 additions & 31 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import path from 'path'
import chalk from 'chalk'
import { Plugin } from '../plugin'
import {
Service,
transform,
Message,
Loader,
TransformOptions,
Expand All @@ -16,30 +16,12 @@ import { createFilter } from '@rollup/pluginutils'

const debug = createDebugger('vite:esbuild')

// lazy start the service
let _servicePromise: Promise<Service> | undefined

export interface ESBuildOptions extends TransformOptions {
include?: string | RegExp | string[] | RegExp[]
exclude?: string | RegExp | string[] | RegExp[]
jsxInject?: string
}

export async function ensureService() {
if (!_servicePromise) {
_servicePromise = require('esbuild').startService()
}
return _servicePromise!
}

export async function stopService() {
if (_servicePromise) {
const service = await _servicePromise
service.stop()
_servicePromise = undefined
}
}

export type ESBuildTransformResult = Omit<TransformResult, 'map'> & {
map: SourceMap
}
Expand All @@ -50,18 +32,17 @@ export async function transformWithEsbuild(
options?: TransformOptions,
inMap?: object
): Promise<ESBuildTransformResult> {
const service = await ensureService()
// if the id ends with a valid ext, use it (e.g. vue blocks)
// otherwise, cleanup the query before checking the ext
const ext = path.extname(
/\.\w+$/.test(filename) ? filename : cleanUrl(filename)
)

let loader = ext.slice(1)
if (loader === 'cjs' || loader === 'mjs') {
loader = 'js'
}

const resolvedOptions = {
loader: loader as Loader,
sourcemap: true,
Expand All @@ -75,7 +56,7 @@ export async function transformWithEsbuild(
delete resolvedOptions.jsxInject

try {
const result = await service.transform(code, resolvedOptions)
const result = await transform(code, resolvedOptions)
if (inMap) {
const nextMap = JSON.parse(result.map)
// merge-source-map will overwrite original sources if newMap also has
Expand Down Expand Up @@ -129,10 +110,6 @@ export function esbuildPlugin(options: ESBuildOptions = {}): Plugin {
map: result.map
}
}
},

async closeBundle() {
await stopService()
}
}
}
Expand All @@ -155,10 +132,6 @@ export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => {
target: target || undefined,
minify
})
},

async closeBundle() {
await stopService()
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2812,10 +2812,10 @@ es-to-primitive@^1.2.1:
is-date-object "^1.0.1"
is-symbol "^1.0.2"

esbuild@^0.8.52:
version "0.8.52"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.8.52.tgz#6dabf11c517af449a96d66da20dfc204ee7b5294"
integrity sha512-b5KzFweLLXoXQwdC/e2+Z80c8uo2M5MgP7yQEEebkFw6In4T9CvYcNoM2ElvJt8ByO04zAZUV0fZkXmXoi2s9A==
esbuild@^0.9.2:
version "0.9.2"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.9.2.tgz#7e9fde247c913ed8ee059e2648b0c53f7d00abe5"
integrity sha512-xE3oOILjnmN8PSjkG3lT9NBbd1DbxNqolJ5qNyrLhDWsFef3yTp/KTQz1C/x7BYFKbtrr9foYtKA6KA1zuNAUQ==

escalade@^3.1.1:
version "3.1.1"
Expand Down

0 comments on commit d3142cf

Please sign in to comment.