import.meta.resolve(specifier)


稳定性: 1.2 - 发布候选版

  • specifier <string> 要相对于当前模块解析的模块说明符。
  • 返回值:<string> 指定符将解析到的绝对 URL 字符串。

import.meta.resolve 是一个模块相对的解析函数,其作用域限定在每个模块内,返回 URL 字符串。

const dependencyAsset = import.meta.resolve('component-lib/asset.css');
// file:///app/node_modules/component-lib/asset.css
import.meta.resolve('./dep.js');
// file:///app/dep.js 

支持 Node.js 模块解析的所有功能。依赖解析需遵循包内允许的导出解析规则。

【All features of the Node.js module resolution are supported. Dependency resolutions are subject to the permitted exports resolutions within the package.】

注意事项

  • 这可能导致同步文件系统操作,其性能影响与 require.resolve 类似。
  • 此功能在自定义加载器中不可用(会导致死锁)。

非标准 API

在使用 --experimental-import-meta-resolve 标志时,该函数接受第二个参数:

【When using the --experimental-import-meta-resolve flag, that function accepts a second argument:】

  • parent <string> | <URL> 可选的绝对父模块 URL,用于解析。 默认值: import.meta.url