Erik
Erik

Reputation: 7352

How to "package" other resources with deno

In deno you can load related modules or other code by just referencing the relative path to those ES6 modules. Deno will handle loading them appropriately. What's the way to do this for non-es6 modules? For example: say I wanted to include some custom css with my deno project? Deno doesn't allow doing import mycss from "./relative.css";.

Deno file operations do work for local files, but they're evaluated relative to the cwd not the current file, and they don't work for arbitrary URLs. fetch, on the other hand, should be perfect, but currently doesn't support file schemes and the decision isn't being actively considered. Combining these yields the only solution I can come up with, but I really don't like it:

async function loadLocal(relative: string): Promise<string> {
  const url = new URL(relative, import.meta.url);
  if (url.protocol === 'file:') {
    return await Deno.readTextFile(url.pathname);
  } else {
    const resp = await fetch(url.href);
    return await resp.text();
  }
}

This seems like it should mostly work, but it seems like a terrible way to hack in something that I expected would be supported by design in deno. It also must be redeclared in each file, or have the callers URL passed in, although there might be a way to avoid that. It doesn't work on windows without modifying the path delimiter.

Update

Deno.emit seems close to what I would want, however for some reason it has different behavior than standard importing:

If the rootSpecifier is a relative path, then the current working directory of the Deno process will be used to resolve the specifier. (Not relative to the current module!)

It also still requires that the paths be to valid modules, instead of arbitrary text.

Upvotes: 2

Views: 498

Answers (1)

Erik
Erik

Reputation: 7352

As @Zwiers pointed out, deno 1.6 now supports fetch with the file protocol, so this is now irrelevant.

Upvotes: 0

Related Questions