Search code examples
javascriptes6-moduleshugoesbuild

What is the best way to point to common dependency from JS modules bundled together?


(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!


Solution

  • 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.