v155 · text modules

Import a file

Four real files from this repository, imported as text. The facts below are read from the imported value — its type, its length, whether it is frozen — because "it is a string" is the whole contract and it is worth confirming rather than assuming.

Pick a file

Checking…

The import

What came back

Choose a file.

the fallback

// A browser without text modules throws on the import, so the fallback
// is a catch rather than a feature test — there is nothing to test.
let text;
try {
  text = (await import(url, { with: { type: "text" } })).default;
} catch (error) {
  if (!(error instanceof TypeError)) throw error;   // a real failure
  text = await (await fetch(url)).text();           // no text modules here
}

Catching broadly would swallow a genuine 404 or a CSP refusal and quietly fall back to a fetch that fails the same way, one layer further from the cause. The narrow catch is what makes the fallback honest.

see also