在本页

import.meta API

Deno 支持 import.meta API 上的许多属性和方法

import.meta.url 跳转到标题

返回当前模块的 URL。

// main.ts
console.log(import.meta.url);
$ deno run main.ts
file:///dev/main.ts

$ deno run https:/example.com/main.ts
https://example.com/main.ts

import.meta.main 跳转到标题

返回当前模块是否为程序的入口点。

// main.ts
import "./other.ts";

console.log(`Is ${import.meta.url} the main module?`, import.meta.main);

// other.ts
console.log(`Is ${import.meta.url} the main module?`, import.meta.main);
$ deno run main.ts
Is file:///dev/other.ts the main module? false
Is file:///dev/main.ts the main module? true

import.meta.filename 跳转到标题

此属性仅适用于本地模块(具有 file:///... 说明符的模块),对于远程模块返回 undefined

返回当前模块的完整解析路径。该值包含操作系统特定的路径分隔符。

// main.ts
console.log(import.meta.filename);

在 Unix 上

$ deno run main.ts
/dev/main.ts

$ deno run https://example.com/main.ts
undefined

在 Windows 上

$ deno run main.ts
C:\dev\main.ts

$ deno run https://example.com/main.ts
undefined

import.meta.dirname 跳转到标题

此属性仅适用于本地模块(具有 file:///... 说明符的模块),对于远程模块返回 undefined

返回包含当前模块的目录的完整解析路径。该值包含操作系统特定的路径分隔符。

// main.ts
console.log(import.meta.dirname);

在 Unix 上

$ deno run main.ts
/dev/

$ deno run https://example.com/main.ts
undefined

在 Windows 上

$ deno run main.ts
C:\dev\

$ deno run https://example.com/main.ts
undefined

import.meta.resolve 跳转到标题

相对于当前模块解析说明符。

const worker = new Worker(import.meta.resolve("./worker.ts"));

import.meta.resolve API 会考虑当前应用的导入映射,这使您能够解析“裸”说明符。

加载了这样的导入映射后...

{
  "imports": {
    "fresh": "https://deno.land/x/fresh@1.0.1/dev.ts"
  }
}

...您现在可以解析

// resolve.js
console.log(import.meta.resolve("fresh"));
$ deno run resolve.js
https://deno.land/x/fresh@1.0.1/dev.ts