Skip to content

Commit

Permalink
fix(optimizer): use simple browser external shim in prod (#8630)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Jun 17, 2022
1 parent d402ad3 commit a32c4ba
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions packages/vite/src/node/optimizer/esbuildDepPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,24 +224,29 @@ export function esbuildDepPlugin(
build.onLoad(
{ filter: /.*/, namespace: 'browser-external' },
({ path }) => {
return {
// Return in CJS to intercept named imports. Use `Object.create` to
// create the Proxy in the prototype to workaround esbuild issue. Why?
//
// In short, esbuild cjs->esm flow:
// 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
// 2. Assign props of `module.exports` to the object.
// 3. Return object for ESM use.
//
// If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
// step 2 does nothing as there's no props for `module.exports`. The final object
// is just an empty object.
//
// Creating the Proxy in the prototype satisfies step 1 immediately, which means
// the returned object is a Proxy that we can intercept.
//
// Note: Skip keys that are accessed by esbuild and browser devtools.
contents: `\
if (config.isProduction) {
return {
contents: 'module.exports = {}'
}
} else {
return {
// Return in CJS to intercept named imports. Use `Object.create` to
// create the Proxy in the prototype to workaround esbuild issue. Why?
//
// In short, esbuild cjs->esm flow:
// 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
// 2. Assign props of `module.exports` to the object.
// 3. Return object for ESM use.
//
// If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
// step 2 does nothing as there's no props for `module.exports`. The final object
// is just an empty object.
//
// Creating the Proxy in the prototype satisfies step 1 immediately, which means
// the returned object is a Proxy that we can intercept.
//
// Note: Skip keys that are accessed by esbuild and browser devtools.
contents: `\
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (
Expand All @@ -254,6 +259,7 @@ module.exports = Object.create(new Proxy({}, {
}
}
}))`
}
}
}
)
Expand Down

0 comments on commit a32c4ba

Please sign in to comment.