Ask coding questions

← Back to all posts
Import Sync [JS/TS]
h
Coder100 (16985)

Import Sync

So, once can programmatically import like this:

const a = await import("urmom-v"+15)

but what if I don't want to await? What if I wanted replicate something like:

const a = require("urmom-v"+15)

thanks bye.

Answered by xxpertHacker (855) [earned 5 cycles]
View Answer
Comments
hotnewtop
xxpertHacker (855)

You cannot synchronously import a file on the web.

The only reason that Node.js can do that is that it has direct access to the user's filesystem.

On the web, blocking the main thread while waiting for an HTTP response would be terrible.

Think of this:

const a = require("./a.js");
const b = require("./b.js");
const c = require("./c.js");

Fire HTTP request for a.js, read the response, parse it, check it's dependencies, then execute the code, then repeat for b.sj and c.js.

Like, dang that would be terrible even if you were on a 5G connection.

In contrast,

import a from "./a.js";
import b from "./b.js";
import c from "./c.js";

fetches and parses everything in parallel.

Coder100 (16985)

(and btw this was in a typescript environment) @xxpertHacker

xxpertHacker (855)

@Coder100 wdym? Was it a Node.js TypeScript environment? If so, the emit should already use require.

xxpertHacker (855)

Btw, appending an (X)HTML script element with .async === false && .defer === false && .type === "text/javascript" might be able to get somewhat close to what you're looking for.

Imperfect, but the closest you'll get.

Example:

const import_file = document.createElement("script");
const remove = "removeAttribute";
import_file[remove]("async");
import_file[remove]("defer");
import_file[remove]("type");

const main = import_file.cloneNode(false);
const set = "setAttribute";
import_file[set]("src", "./import.js");
main[set]("src", "./main.js");

That was painful to write, don't actually do that.