Import Maps,现已在所有浏览器中可用,改进了JavaScript中的模块解析

Safari 16.4 支持 Import Maps

Safari 16.4 最近添加了对 Import Maps 的支持,这意味着 JavaScript 开发者现在可以在所有现代浏览器中使用 Import Maps。对于不支持该功能的旧版浏览器,可以使用 es-module-shims 作为 polyfill。Import Maps 为 JavaScript 应用程序带来了更好的模块解析能力。

Import Maps 的作用

Import Maps 允许开发者以自定义方式解析模块标识符,从而将模块依赖的引用与其实际位置(磁盘或远程服务器)分离。开发者可以使用裸模块标识符(如 import { pluck } from "lodash";)来导入依赖,而无需在应用代码中手动处理依赖的映射关系。

JSPM CLI 的重新发布

随着跨浏览器支持的实现,JSPM CLI 最近重新发布,作为一款 Import Maps 包管理工具。例如,JSPM CLI 可以自动为 lit 库生成以下 Import Map:

<script type="importmap">
{
  "imports": {
    "lit": "https://ga.jspm.io/npm:lit@2.7.0/index.js"
  },
  "scopes": {
    "https://ga.jspm.io/": {
      "@lit/reactive-element": "https://ga.jspm.io/npm:@lit/reactive-element@1.6.1/reactive-element.js",
      "lit-element/lit-element.js": "https://ga.jspm.io/npm:lit-element@3.3.0/lit-element.js",
      "lit-html": "https://ga.jspm.io/npm:lit-html@2.7.0/lit-html.js",
      "lit-html/is-server.js": "https://ga.jspm.io/npm:lit-html@2.7.0/is-server.js"
    }
  }
}
</script>

开发者体验的提升

Guy Bedford,JSPM CLI 的核心开源贡献者,也是 Import Maps polyfill 的维护者,解释了 Import Maps 如何提升开发者体验:

  • JSPM 支持 package.json 中的版本范围,并兼容 Node.js 模块解析的所有特性。
  • 它支持任意模块 URL 和 CDN 提供商(如 unpkg 或本地 node_modules 映射)。
  • 减少了开发者与工具之间的步骤,缩短了开发与生产之间的距离,提升了应用与最终用户之间的效率。

手动提供 Import Maps

开发者也可以手动提供 Import Maps,从而在某些情况下无需使用构建工具。Lit 团队在 Twitter 上提供了一个示例,展示了如何通过 Import Maps 实现前端开发而无需安装 npm 包。

Import Maps 的规范

Import Maps 的 WhatWG 规范 定义了一种基于 JSON 对象的模块解析机制,包含 importsscopes 两个字段。例如:

{
  "imports": {
    "a": "/a-1.mjs",
    "b": "/b-1.mjs",
    "c": "/c-1.mjs"
  },
  "scopes": {
    "/scope2/": {
      "a": "/a-2.mjs"
    },
    "/scope2/scope3/": {
      "b": "/b-3.mjs"
    }
  }
}

该 Import Map 会根据脚本的位置和模块标识符解析出正确的模块地址。

在 HTML 中使用 Import Maps

Import Maps 通过 <script type="importmap"> 标签嵌入到 HTML 文件的 <head> 部分:

<!doctype html>
<script type="importmap">
... JSON import map here
</script>

对于不支持 Import Maps 的旧版浏览器,可以使用 es-module-shims 作为 polyfill。

浏览器支持检测

开发者可以通过以下代码检测浏览器是否支持 Import Maps:

if (HTMLScriptElement.supports('importmap')) {
  // 浏览器支持 Import Maps
}

更多技术细节可以参考 Import Maps 规范

阅读 39
0 条评论