Chrome扩展开发中@notionhq/client模块导入错误求助
Chrome扩展中Notion Client模块解析与MIME错误的解决方案
问题根源
- Chrome扩展的脚本环境不支持Node.js的裸模块导入规则(如
@notionhq/client),仅识别相对/绝对路径的模块引用。 - 引用
.d.ts文件是错误操作:这是TypeScript类型声明文件,并非可执行JavaScript模块,浏览器会将其识别为纯文本,导致MIME类型错误。
具体解决方案
方案1:使用打包工具(推荐,适合长期维护)
用Vite、Webpack等工具将依赖打包为浏览器兼容的模块,消除裸导入问题:
- 初始化打包项目(以Vite为例):
npm create vite@latest my-extension -- --template vanilla cd my-extension npm install @notionhq/client - 修改
vite.config.js,指定输出目录为扩展的资源目录:import { defineConfig } from 'vite' export default defineConfig({ build: { outDir: '../extension/dist', // 指向你的Chrome扩展目录下的dist文件夹 emptyOutDir: true } }) - 在你的业务脚本中正常导入Notion Client:
import { Client } from '@notionhq/client' // 后续业务代码 - 执行
npm run build打包,然后在Chrome扩展的manifest.json中引用打包后的文件:"content_scripts": [ { "matches": ["<all_urls>"], "js": ["dist/main.js"] } ]
方案2:手动引入UMD格式的Notion Client
- 找到
node_modules/@notionhq/client/build/umd/notion-client.js文件,复制到你的Chrome扩展目录(如lib/文件夹)。 - 在业务脚本中用相对路径引入该文件:
import './lib/notion-client.js' - 通过全局变量调用Notion Client:
const notion = new window.NotionClient.Client({ auth: '你的Notion密钥' })
方案3:CDN直接引入
- 在
manifest.json的脚本配置中添加CDN地址,确保CSP允许该域名:"content_security_policy": { "extension_pages": "script-src 'self' https://cdn.jsdelivr.net; object-src 'none'" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["https://cdn.jsdelivr.net/npm/@notionhq/client@2.2.13/build/umd/notion-client.js", "your-script.js"] } ] - 在
your-script.js中直接使用全局变量:const notion = new window.NotionClient.Client({ auth: '你的Notion密钥' })
关键注意事项
- 绝对不要引用
.d.ts类型声明文件,运行时仅需JavaScript文件。 - 若使用CDN,需在CSP中添加对应域名,否则Chrome会拦截脚本加载。
- 打包工具需配置正确的输出路径,确保
manifest.json能正确指向打包后的资源。
内容的提问来源于stack exchange,提问作者Sanket Bhat
相关产品推荐
相关产品推荐

