Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting Bundled node_modules Separately from Source #2321

Closed
mildaniel opened this issue Jun 15, 2022 · 3 comments
Closed

Getting Bundled node_modules Separately from Source #2321

mildaniel opened this issue Jun 15, 2022 · 3 comments

Comments

@mildaniel
Copy link

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?

@evanw
Copy link
Owner

evanw commented Jun 16, 2022

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:

  1. Bundle your code once with a plugin that records dependencies, and throw the bundle away
  2. Bundle once with a generated entry point that just imports and re-exports all dependencies from step 1
  3. 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.

@hyrious
Copy link

hyrious commented Jun 16, 2022

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

  1. Scan deps. Most of the time pkg.dependencies is what we want. It can be fixed by doing bundle once like evan said, which is easy.

  2. Lazily-initialized modules. It can be fixed with:

    Object.defineProperty(__vendors__, "mod", {
      get: () => require("mod"),
      enumerable: true
    })
    // instead of
    // __vendors__.mod = require("mod")

@evanw
Copy link
Owner

evanw commented Sep 12, 2022

Closing because this was answered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants