Bun

import.meta

import.meta 物件是一種讓模組存取自身資訊的方法。它是 JavaScript 語言的一部分,但其內容並未標準化。每個「主機」(瀏覽器、執行時期等)都可以在 import.meta 物件上實作任何它想要的屬性。

Bun 實作了以下屬性。

/path/to/project/file.ts
import.meta.dir;   // => "/path/to/project"
import.meta.file;  // => "file.ts"
import.meta.path;  // => "/path/to/project/file.ts"
import.meta.url;   // => "file:///path/to/project/file.ts"

import.meta.main;  // `true` if this file is directly executed by `bun run`
                   // `false` otherwise

import.meta.resolve("zod"); // => "file:///path/to/project/node_modules/zod/index.js"
import.meta.dir包含目前檔案的目錄的絕對路徑,例如 /path/to/project。等同於 CommonJS 模組(和 Node.js)中的 __dirname
import.meta.dirnameimport.meta.dir 的別名,用於與 Node.js 相容
import.meta.envprocess.env 的別名。
import.meta.file目前檔案的名稱,例如 index.tsx
import.meta.path目前檔案的絕對路徑,例如 /path/to/project/index.ts。等同於 CommonJS 模組(和 Node.js)中的 __filename
import.meta.filenameimport.meta.path 的別名,用於與 Node.js 相容
import.meta.main指出目前檔案是否是目前 bun 程序的進入點。檔案是由 bun run 直接執行,還是被匯入的?

import.meta.resolve

將模組規格(例如 "zod""./file.tsx")解析為 URL。等同於 瀏覽器中的 import.meta.resolve

import.meta.resolve("zod");
// => "file:///path/to/project/node_modules/zod/index.ts"
import.meta.url目前檔案的 字串 URL,例如 file:///path/to/project/index.ts。等同於 瀏覽器中的 import.meta.url