Skip to content

Commit

Permalink
Update plugin to bundle .node modules
Browse files Browse the repository at this point in the history
  • Loading branch information
lpsinger committed Dec 16, 2024
1 parent 2359f82 commit 78d037f
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions esbuild.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import esbuild from 'esbuild'
import { copyFile, writeFile } from 'fs/promises'
import { access, copyFile, unlink, writeFile } from 'fs/promises'
import { glob } from 'glob'
import { extname } from 'node:path'
import { basename, dirname, join } from 'path'
Expand Down Expand Up @@ -27,21 +27,40 @@ const options = {
sourcemap: true,
sourcesContent: false,
metafile: true,
loader: { '.node': 'empty' },
loader: { '.node': 'copy' },
publicPath: './',
plugins: [
{
name: 'copy Node API modules to output directories',
setup(build) {
build.onResolve({ filter: /\.node$/ }, async ({ path, resolveDir }) => {
// Skip .node modules that don't exist. @mongodb-js/zstd tries to
// import Release/zstd.node and falls back to Debug/zstd.node; the
// latter does not exist on production builds.
const resolvedPath = import.meta.resolve(path, resolveDir)
try {
await access(resolvedPath)
} catch {
return { path: '/dev/null', external: true }
}
})
build.onEnd(async ({ metafile: { outputs } }) => {
// Copy bundled .node modules from outdir to the Lambda directory.
await Promise.all(
Object.entries(outputs).flatMap(([entryPoint, { inputs }]) =>
Object.keys(inputs)
.filter((input) => extname(input) === '.node')
.map((input) =>
copyFile(input, join(dirname(entryPoint), basename(input)))
Object.entries(outputs).flatMap(([entryPoint, { imports }]) =>
imports
.filter(({ path }) => extname(path) === '.node')
.map(({ path }) =>
copyFile(path, join(dirname(entryPoint), basename(path)))
)
)
)
// Delete .node modules in outdir.
await Promise.all(
Object.keys(outputs)
.filter((path) => extname(path) === '.node')
.map(unlink)
)
})
},
},
Expand Down

0 comments on commit 78d037f

Please sign in to comment.