Skip to content

Commit

Permalink
Mark the injected shim as internal for esbuild
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmyersdev committed Jan 10, 2023
1 parent ae1de27 commit c033fde
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ interface PolyfillOptions {
*/
export const nodePolyfills = (options: Partial<PolyfillOptions> = {}): Plugin => {
const require = createRequire(import.meta.url)
const globalShims = require.resolve('node-stdlib-browser/helpers/esbuild/shim')
const globalShimsPath = require.resolve('node-stdlib-browser/helpers/esbuild/shim')
const optionsResolved: PolyfillOptions = {
protocolImports: true,
// User options take priority.
Expand Down Expand Up @@ -65,9 +65,9 @@ export const nodePolyfills = (options: Partial<PolyfillOptions> = {}): Plugin =>
{
...inject({
// https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md#vite
global: [globalShims, 'global'],
process: [globalShims, 'process'],
Buffer: [globalShims, 'Buffer'],
global: [globalShimsPath, 'global'],
process: [globalShimsPath, 'process'],
Buffer: [globalShimsPath, 'Buffer'],
}),
},
],
Expand All @@ -82,10 +82,29 @@ export const nodePolyfills = (options: Partial<PolyfillOptions> = {}): Plugin =>
process: 'process',
},
inject: [
globalShims,
globalShimsPath,
],
plugins: [
esbuildPlugin(polyfills),
// Supress the 'injected path "..." cannot be marked as external' error in Vite 4 (emitted by esbuild).
// https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1469
{
name: 'vite-plugin-node-polyfills-shims-resolver',
setup(build) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
const escapedGlobalShimsPath = globalShimsPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const filter = new RegExp(`^${escapedGlobalShimsPath}$`)

// https://esbuild.github.io/plugins/#on-resolve
build.onResolve({ filter }, () => {
return {
// https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1468
external: false,
path: globalShimsPath,
}
})
},
},
],
},
},
Expand Down

0 comments on commit c033fde

Please sign in to comment.