Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix: enable failing dependencies to be optimised by pre-processing th…
…em with esbuild (#4275)
  • Loading branch information
fwouts committed Aug 23, 2021
1 parent 8048f90 commit ea98a1a
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions packages/vite/src/node/optimizer/index.ts
Expand Up @@ -15,6 +15,7 @@ import {
import { esbuildDepPlugin } from './esbuildDepPlugin'
import { ImportSpecifier, init, parse } from 'es-module-lexer'
import { scanImports } from './scan'
import { transformWithEsbuild } from '../plugins/esbuild'

const debug = createDebugger('vite:deps')

Expand Down Expand Up @@ -237,12 +238,32 @@ export async function optimizeDeps(
const idToExports: Record<string, ExportsData> = {}
const flatIdToExports: Record<string, ExportsData> = {}

const { plugins = [], ...esbuildOptions } =
config.optimizeDeps?.esbuildOptions ?? {}

await init
for (const id in deps) {
const flatId = flattenId(id)
flatIdDeps[flatId] = deps[id]
const entryContent = fs.readFileSync(deps[id], 'utf-8')
const exportsData = parse(entryContent) as ExportsData
const filePath = (flatIdDeps[flatId] = deps[id])
const entryContent = fs.readFileSync(filePath, 'utf-8')
let exportsData: ExportsData
try {
exportsData = parse(entryContent) as ExportsData
} catch {
debug(
`Unable to parse dependency: ${id}. Trying again with a JSX transform.`
)
const transformed = await transformWithEsbuild(entryContent, filePath, {
loader: 'jsx'
})
// Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
// This is useful for packages such as Gatsby.
esbuildOptions.loader = {
'.js': 'jsx',
...esbuildOptions.loader
}
exportsData = parse(transformed.code) as ExportsData
}
for (const { ss, se } of exportsData[0]) {
const exp = entryContent.slice(ss, se)
if (/export\s+\*\s+from/.test(exp)) {
Expand All @@ -263,9 +284,6 @@ export async function optimizeDeps(

const start = Date.now()

const { plugins = [], ...esbuildOptions } =
config.optimizeDeps?.esbuildOptions ?? {}

const result = await build({
absWorkingDir: process.cwd(),
entryPoints: Object.keys(flatIdDeps),
Expand Down

0 comments on commit ea98a1a

Please sign in to comment.