Getting Bundled node_modules Separately from Source
Hi @evanw,
Our use case is a little different from the typical front-end use cases in that we want to use esbuild to build and package JS and TS to be used in something like AWS Lambda. We want the source code to be in a single bundle and all external dependencies still bundled and minified but in a separate file. Is there any way to currently do this using esbuild?
You're correct that this is not something esbuild does. You could probably figure out something with the plugin API: https://esbuild.github.io/plugins/. I'm imagining something like this:
- Bundle your code once with a plugin that records dependencies, and throw the bundle away
- Bundle once with a generated entry point that just imports and re-exports all dependencies from step 1
- Bundle your code once with a plugin that substitutes each dependency with a stub that imports the dependency from the file in step 2
For correctness you may need the dependencies in the bundle in step 2 to be lazily-initialized (if they have side effects and/or are supposed to only be conditionally imported). You could do that by e.g. re-exporting them as a function that calls require() instead of re-exporting the result of the require() call directly.
Here's a dead-simple example of doing manual chunks (#207) by yourself: esbuild-split-vendors-example
It doesn't include some more complex logic like
-
Scan deps. Most of the time
pkg.dependenciesis what we want. It can be fixed by doing bundle once like evan said, which is easy. -
Lazily-initialized modules. It can be fixed with:
Object.defineProperty(__vendors__, "mod", { get: () => require("mod"), enumerable: true }) // instead of // __vendors__.mod = require("mod")
Closing because this was answered.