import.meta 是 es 模块中由引擎自动提供的只读对象,最常用 import.meta.url 获取模块绝对 url;浏览器中为 http/https/data 开头,node.js 中为 file:// 开头,可配合 url/path 模块还原 __dirname,亦可用于环境判断及工具链扩展属性。

import.meta 是 ES 模块中一个只读对象,由 JavaScript 引擎在每个模块作用域内自动提供,用于访问当前模块的元信息,最常用的是 import.meta.url 获取模块的完整 URL(如 file:///path/to/module.js 或 https://example.com/script.js)。
获取当前模块的 URL(最常见用途)
在浏览器或支持 ES 模块的 Node.js(v12.20+,推荐 v14.13+)中,import.meta.url 返回模块的绝对 URL,可用于动态加载资源、构造相对路径、判断运行环境等:
- 浏览器中:
import.meta.url是模块脚本的完整地址,例如https://site.com/js/main.mjs - Node.js 中:
import.meta.url是file://协议的绝对路径,例如file:///home/user/project/src/index.js - 注意:它不是字符串字面量,不能直接拼接路径;需用
new URL('./assets/', import.meta.url)构造正确路径
在 Node.js 中解析模块所在目录(替代 __dirname)
CommonJS 中常用 __dirname,但 ES 模块中不可用。可用 import.meta.url 配合内置模块还原:
- Node.js(ESM)中获取当前模块所在文件夹路径:
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
之后即可使用 __dirname 做 require 替代(如读取本地 JSON)、构建路径等。
检查模块运行环境(浏览器 vs Node.js)
虽然不推荐过度检测环境,但 import.meta 可辅助判断上下文:
- 浏览器中:
import.meta.url以http://、https://或data:开头 - Node.js 中:
import.meta.url以file://开头 - 可简单判断:
const isNode = import.meta.url.startsWith('file://');
其他可能存在的 import.meta 属性(非标准,依环境而定)
import.meta 是可扩展对象,不同运行时可能添加自有属性:
- Vite:提供
import.meta.env(含VITE_APP_TITLE等注入变量) - Webpack 5+:支持
import.meta.webpackHot(HMR 相关) - Rollup / esbuild:通常只保证
import.meta.url,其余为空对象 - ⚠️ 注意:
import.meta.xxx不是语言标准,跨工具时需谨慎依赖
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











