import.meta是es模块中由引擎注入的只读元数据对象,仅在模块顶层可用,非全局变量;核心属性import.meta.url返回当前模块绝对url,需配合new url()安全解析路径,且仅在esm上下文中有效。

import.meta 是 ES 模块(ESM)执行上下文中由 JavaScript 引擎自动注入的只读元数据对象,它不是全局变量,也不属于 window 或 globalThis,仅在模块作用域顶层可用。它的核心价值在于让模块“知道自己在哪”,尤其解决了 ESM 中缺失 __dirname 和 __filename 的问题。
import.meta.url:唯一跨平台标准属性
这是目前所有主流环境(浏览器、Node.js v12.20+ / v14.13+、Deno、Bun)都原生支持的属性,返回当前模块的绝对 URL 字符串:
- 浏览器中为
https://、http://或file://开头,精确对应脚本加载地址 - Node.js 中恒为
file://协议,路径含完整盘符(Windows)或根路径(Unix),如file:///home/user/app/index.js - 不能直接字符串截取解析路径——协议格式、编码规则、大小写敏感性因环境而异
- 推荐配合
new URL()使用:new URL('./config.json', import.meta.url)可安全解析同目录资源
模块环境是前提:非模块脚本中不可用
import.meta 严格绑定于 ESM 执行上下文,以下情况会报 ReferenceError: import.meta is not defined:
- 普通
<script></script>标签(未声明type="module") - CommonJS 文件(
.cjs或package.json中未设"type": "module") - Node.js 中以
node script.js方式运行(默认 CJS),需改用node --input-type=module -e "..."或重命名.mjs - Vite/Webpack 等工具若配置了
target: 'es5',可能移除该特性,需检查构建目标版本
环境扩展属性:非标准,但实用
import.meta 本身是可扩展对象,不同运行时或构建工具可注入自定义字段,但这些属性不可跨平台假设存在:
-
Vite 注入
import.meta.env(含PROD、DEV、BASE_URL等),构建时静态替换;开发时为普通对象,需if ('env' in import.meta)判断 -
Node.js v20+ 实验性支持
import.meta.resolve(),用于模块路径解析(类似require.resolve()) -
Deno 提供
import.meta.main(是否为主模块)、import.meta.dirname(需--unstable) -
浏览器 支持
import.meta.scriptElement,返回加载该模块的<script type="module"></script>元素
典型使用场景
基于 import.meta.url 的路径能力,常见落地方式包括:
- 动态加载同目录资源:
fetch(new URL('./data.json', import.meta.url)) - 创建 Web Worker:
new Worker(new URL('./worker.js', import.meta.url)) - Node.js 读取本地文件:
readFile(new URL('./config.yaml', import.meta.url)) - 推导模块所在目录(替代
__dirname):const __dirname = new URL('.', import.meta.url).pathname - 判断运行环境:
import.meta.url.startsWith('file://')→ 本地运行;.startsWith('https://')→ 生产部署











