import.meta.resolve(specifier)


版本历史
版本变更
v20.6.0, v18.19.0

不再落后于 --experimental-import-meta-resolve CLI 标志,非标准 parentURL 参数除外。

v20.6.0, v18.19.0

当目标 file: URL 未映射到本地 FS 上的现有文件时,此 API 不再抛出异常。

v20.0.0, v18.19.0

此 API 现在同步返回字符串而不是 Promise。

v16.2.0, v14.18.0

parentURL 参数添加对 WHATWG URL 对象的支持。

v13.9.0, v12.16.2

新增于: v13.9.0, v12.16.2

稳定性: 1.2 - 发布候选

\Stability: 1.2 - Release candidate

  • specifier <string> 相对于当前模块解析的模块说明符。

    \specifier <string> The module specifier to resolve relative to the current module.

  • 返回:<string> 说明符将解析为的绝对 URL 字符串。

    \Returns: <string> The absolute URL string that the specifier would resolve to.

import.meta.resolve 是一个模块相对解析函数,作用域为每个模块,返回 URL 字符串。

\import.meta.resolve is a module-relative resolution function scoped to each module, returning the URL string.

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.

注意事项:

\Caveats:

  • 这可能会导致同步文件系统操作,从而对性能产生类似于 require.resolve 的影响。

    \This can result in synchronous file-system operations, which can impact performance similarly to require.resolve.

  • 此功能在自定义加载程序中不可用(这会造成死锁)。

    \This feature is not available within custom loaders (it would create a deadlock).

非标准 API:

\Non-standard 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

    \parent <string> | <URL> An optional absolute parent module URL to resolve from. Default: import.meta.url

AltStyle によって変換されたページ (->オリジナル) /