-1

I wonder if there a standard way to bundle native ES modules.

Suppose I have such a "brilliant" project (just for example):

<!-- index.html -->
<script type="module" src="./main.js"></script>

// main.js
import value from "./lib.js"

console.log(value);

// lib.js
export default 'hello world';

Now it needs three requests to load — it's too much, I need only two — .html and .js.

It looks simple at first glance (cat *.js > bundle.js) but there is no syntax for multiple ES modules in one file (as I can see).

I know I can translate ES modules syntax to some other module system (e. g. AMD) and then bundle them but it isn't what I want.

I am curious to accomplish this by native module features only. As simple and handmade as possible.

Is there a way to do this? Maybe at least a proposal?

Thank you.

shau-kote
  • 1,110
  • 3
  • 12
  • 24
  • 2
    With the advent of HTTP/2 and its ability to pipeline and multiplex requests, the need for bundling is much reduced. What was mentioned in [How do you build, bundle & minify ES6-modules?](https://stackoverflow.com/q/45400636/215552) holds true even today. – Heretic Monkey Feb 18 '19 at 18:34
  • @HereticMonkey I agree that HTTP/2 have reduced the significance of bundling. But not ultimately. From my point of view, bundling is still a very important part of client-side module system, I was surprised there does not exist something similar in ES spec. – shau-kote Feb 18 '19 at 18:40

2 Answers2

2

rollup supports ESM as an output format as well. Your example transpiles to a simple script, but if you have exports in your entry module it will keep them.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thank you for the answer and the example! Rollup build an one ESM from my modules, am I correct? What about module isolation (in more complex system)? – shau-kote Feb 18 '19 at 18:45
  • What do you mean by "module isolation", that a single file could contain multiple module sources that could be imported individually? I do not know of any such file format, on the web HTTP/2 is supposed to solve this. – Bergi Feb 18 '19 at 18:48
  • (It can build an ESM, but...) you use the bundle in a ` – P Varga Feb 18 '19 at 18:48
  • Create another simple example (bit.ly/2tsr9Ry). As I expected, isolation is made via some ugly tricks. :( – shau-kote Feb 18 '19 at 18:51
  • @Bergi I have posted an example above. Sorry for the tricky link, the data url was too long. :( The example consist of two modules, both have a top-level variables with the same name. – shau-kote Feb 18 '19 at 18:54
  • 1
    @shau-kote Ah, yes, Rollup properly conserves the specified module behaviour concerning scopes, hoisting, evaluation order etc. using the usual transpiler tricks. – Bergi Feb 18 '19 at 18:56
1

rollup, webpack etc natively understand and can bundle ES modules.

P Varga
  • 19,174
  • 12
  • 70
  • 108