开发Chrome扩展时如何使用importmap并解决Three.js插件导入问题
解决Chrome扩展Manifest V3中importmap的CSP违规问题
一、调整CSP配置允许importmap
Manifest V3对inline脚本的限制比V2严格,单纯加'unsafe-inline'无法生效,需要配合'unsafe-hashes'和importmap脚本的具体哈希值:
先获取你的importmap脚本的SHA-256哈希:
把页面中实际的importmap代码(包括换行和空格)复制出来,用哈希工具计算SHA-256值。比如你的importmap是:<script type="importmap"> { "imports": { "three": "./libs/three.module.js" } } </script>计算这段内容的哈希,得到类似
'sha256-abcdef123456...'的字符串。修改manifest.json的CSP配置:
"content_security_policy": { "script-src": "'self' 'unsafe-hashes' 'sha256-你的哈希值'", "script-src-elem": "'self' 'sha256-你的哈希值'" }这里
'unsafe-hashes'是必须的,因为Manifest V3默认不允许通过哈希信任inline脚本,需要声明开启这个规则。
二、不用importmap的替代方案
如果不想折腾CSP,也可以用下面的方法绕过importmap需求:
修改插件导入路径:如果插件是你可以编辑的,直接把插件里的
import ... from 'three'改成指向three.module.js的相对路径,比如import * as THREE from '../libs/three.module.js',这样就不需要importmap做映射了。用打包工具配置别名:用Webpack、Vite这类工具打包扩展时,配置模块别名,把
'three'映射到实际的three.js模块路径。比如Vite的配置示例:export default { resolve: { alias: { 'three': './src/libs/three.module.js' } } }打包后所有插件中的
'three'导入都会被自动替换成正确路径,完美避开importmap的问题。
内容的提问来源于stack exchange,提问作者Tinkerbell
相关产品推荐
相关产品推荐

