2

(Code below is a simple example, real scenario is bigger)

I have two modules, mod1.js and mod2.js, which are bundled together (using esbuild). They share a common dependency, util.js.

Problem is: when code in mod2.js imports util.js (using same alias), there's a conflict with names.

util.js:

export class Util {
  ...
}

mod1.js:

import Util from "./util.js";
...

mod2.js:

/* this raises an error of variable already declared */
import Util from "./util.js";
...

If I change alias in mod2.js, error goes away, as expected. But changing aliases every time I import util.js is a bit clumsy, and makes me think there has to be another way.

Is there a better approach to point to a common dependency from multiple modules which are bundled together?

Thanks in advance!

  • 2
    This is not a problem with your code, rather with the `esbuild` tool. How are you using it, what output format did you choose? Also it's feature list mentions "*Scope hoisting for ES6 modules*", which might cause this. – Bergi Jul 31 '20 at 02:28
  • 1
    Yes, the docs for [ES6 linking](https://github.com/evanw/esbuild/blob/master/docs/architecture.md#es6-linking) and [scope hoisting](https://github.com/evanw/esbuild/blob/master/docs/architecture.md#scope-hoisting) confirm my hunch. How exactly are you "bundling" your two modules *mod1.js* and *mod2.js* "together"? What single entrypoint do you use? Have you taken a look at [code splitting](https://github.com/evanw/esbuild/blob/master/docs/architecture.md#code-splitting)? – Bergi Jul 31 '20 at 02:33
  • Thanks, @Bergi! In fact, I'm using `esbuild` through [Hugo](https://gohugo.io/hugo-pipes/js/). The script files are [concatenated](https://gohugo.io/hugo-pipes/bundling/#readout) *before* passing them to `esbuild`. I realize now that I'm bypassing `esbuild` bundling by making this step with Hugo... And the format I use for `esbuild` is `iife`. – José de Mattos Neto Jul 31 '20 at 02:54

1 Answers1

4

With help from @Bergi's comment, I figured out that I was not using esbuild to bundle my files, but rather using Hugo to concatenate them, and passing this to esbuild.

This leads to mentioned error because there are multiple imports in the same file, which esbuild correctly doesn't recognize as valid. Instead, using esbuild to bundle my files gives me correct results.

I'm still using Hugo, but I have a single entry point which it consumes, that imports all my scripts. From example, I have another file, say master.js:

master.js:

import mod1 from "./mod1.js";
import mod2 from "./mod2.js";

And I then pass this master.js to Hugo, using its js.Build function, which internally uses esbuild. This way I can import util.js using same alias, because these imports are in separate files, using ES6 linking from esbuild.