evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
37.94k stars 1.13k forks source link

output does not contain all imports #2307

Closed MoritzLoewenstein closed 1 year ago

MoritzLoewenstein commented 2 years ago

I am pretty sure I am missing something, but heres my problem:

// a.js
import "./b.js"
// b.js
function sum(a, b) {
  return a + b;
}
// build.js
import esbuild from "esbuild";
esbuild.buildSync({
  entryPoints: ["a.js"],
  treeShaking: false,
  minify: false,
  bundle: true,
  outfile: "out.js",
});
// out.js
(() => {
})();

I am just trying to achieve this: " To join a set of files together with esbuild, import them all into a single entry point file and bundle just that one file with esbuild.". I tried to add sideEffects: ["*.js"] to package.json, but it didnt change anything. If this is the expected behaviour, can I preserve the function from b.js in the output with other available options?

evanw commented 2 years ago

You have encountered "tree shaking" also known as "dead code removal." There is no observable difference between this code:

(() => {
  function sum(a, b) {
    return a + b;
  }
}();

and this code:

(() => {
})();

so during bundling, esbuild automatically omits the dead code for you. If you want sum to be present in the output, you'll have to use it somehow. You should either call it or export it so that some other code can call it.

Note that all three of esbuild's output formats (iife, cjs, esm) are some form of module that encapsulates local unexported state. There is no "global" output format that automatically exposes exports as properties on the global object. Which output format you choose depends on how the output file will be used.

MoritzLoewenstein commented 2 years ago

That makes a lot of sense, I just thought treeShaking: false would disable all kinds of code removal.

The problem is that I currently remove the iife to interact with the code from script tags inside php (inserting global variables, calling functions etc.). Since this probably isnt a problem for other users of esbuild, I will just work around my problem for now.

evanw commented 1 year ago

Closing this issue as out of scope. It's deliberate that esbuild only supports non-global module-oriented output formats.