Firefox v107中es-module-shims polyfill的Import Map动态导入失效
问题描述
我在网站中使用Import Map,根据caniuse的信息,Firefox v107及非技术预览版Safari不支持该特性。我原本以为es-module-shims polyfill库可以提供支持,但实际没生效。当在about:config中启用Import Map(或用Chrome访问页面)时代码运行正常,但Firefox v107控制台会抛出错误。我是不是错误使用了polyfill,或是用了不被支持的功能?
页面中的代码如下:
<script src="//unpkg.com/es-module-shims/dist/es-module-shims.js"></script> <script type="importmap"> { "imports": { "three/examples/fonts/": "./node_modules/three/examples/fonts/", "three/examples/jsm/": "./node_modules/three/examples/jsm/", "three": "./node_modules/three/build/three.module.js" } } </script> <script type="module" defer src="index.js"></script>
我的index.js中有动态导入代码:
if (location.pathname === "/" || location.pathname === "/index.html") { import("./module/hero.js"); }
在module/hero.js顶部有Three.js的静态导入:
import * as THREE from "three";
解决方案
问题出在es-module-shims的使用方式上——原生不支持Import Map的浏览器需要特殊的script类型标识,才能让polyfill生效。你需要做两处修改:
- 把
type="importmap"改成type="importmap-shim" - 把模块脚本的
type="module"改成type="module-shim"
修改后的代码:
<script src="//unpkg.com/es-module-shims/dist/es-module-shims.js"></script> <script type="importmap-shim"> { "imports": { "three/examples/fonts/": "./node_modules/three/examples/fonts/", "three/examples/jsm/": "./node_modules/three/examples/jsm/", "three": "./node_modules/three/build/three.module.js" } } </script> <script type="module-shim" defer src="index.js"></script>
补充说明:
- es-module-shims会自动识别浏览器是否原生支持Import Map,支持的浏览器会直接用原生实现,无需额外调整
- 动态导入和静态导入的语法保持原样即可,polyfill会自动处理路径映射
内容的提问来源于stack exchange,提问作者Arcanist
相关产品推荐
相关产品推荐

