nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
107.86k stars 29.72k forks source link

util function to statically resolve ESM dependency trees #34486

Open nmalyschkin opened 4 years ago

nmalyschkin commented 4 years ago

What:

Add a utlilty function to resolve ECMAScript Module dependency trees. The function should accept a file path and return an array of dependencies.

example

// main.mjs
import bar from "./bar.mjs";
import foo from "./foo.mjs";

// bar.mjs
import foo from "./foo.mjs";
export null;

// foo.mjs
export null;
const { resolveDependencies } = require("util");

const dependencies = await resolveDependencies("main.mjs");
assert.deepStrictEqual(dependencies, ["./bar.mjs", "./foo.mjs"]);

How:

Use the existing code that resolves dependencies for imports.

Mixing CJS and ESM is not possible, since CJS modules are loaded on execution.

Why:

When loading ESM files from clients like browsers or node to execute them, every layer of the dependency tree is loaded sequentially leading to slower load times. Servers could resolve the dependencies beforehand and use mechanisms like HTTP/2 Push to send all needed files directly. This way we can achive load times similar to bundled applications without the hassle of bundling. We can use imperative imports to load parts of our application on demand without the need of chunking.

In the long run this could have larger implications. If we can avoid using bundlers to deploy applications we could use CDNs and caches more effectively.

devsnek commented 4 years ago

It's surprisingly easy. Check out https://github.com/devsnek/http2-push-parser/blob/master/index.js