import.meta.resolve(specifier)


稳定性: 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