如何使用 deno "package" 其他资源

How to "package" other resources with deno

在 deno 中,您可以通过引用这些 ES6 模块的相对路径来加载相关模块或其他代码。 Deno 将适当地处理加载它们。对于非 es6 模块,有什么方法可以做到这一点?例如:假设我想在我的 deno 项目中包含一些自定义 css? Deno 不允许 import mycss from "./relative.css";.

Deno 文件操作确实适用于本地文件,但它们是相对于 cwd 而不是当前文件进行评估的,并且它们不适用于任意 URLs。 fetch,另一方面,应该是完美的,但目前不支持文件方案和决定isn't being actively considered。结合这些产生了我能想出的唯一解决方案,但我真的不喜欢它:

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();
  }
}

这似乎应该大部分都有效,但它似乎是一种糟糕的方式来破解我期望 deno 设计会支持的东西。它也必须在每个文件中重新声明,或者让调用者 URL 传入,尽管可能有办法避免这种情况。如果不修改路径定界符,它在 windows 上不起作用。

更新

Deno.emit 似乎接近我想要的,但是由于某种原因,它的行为与标准导入不同:

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!)

它仍然要求路径是有效模块,而不是任意文本。

正如@Zwiers 指出的那样,deno 1.6 现在支持使用 file 协议获取数据,所以现在这无关紧要了。