我正在使用 Vite、React 和 TypeScript 开发 Chrome 扩展。该扩展包括一个我想注入到活动选项卡中的内容脚本。但是,当内容脚本运行时,我遇到以下错误:
Uncaught (in promise) Error: Cannot use import statement outside a module at content.js:1:1
vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path';
import { viteStaticCopy } from 'vite-plugin-static-copy'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
viteStaticCopy({
targets: [
{
src: 'manifest.json',
dest: ''
}
]
})
],
build: {
outDir: 'dist',
rollupOptions: {
input: {
popup: resolve(__dirname, 'index.html'),
background: resolve(__dirname, "src/background.ts"),
content: resolve(__dirname, 'src/content.tsx'),
chat: resolve(__dirname, 'src/chat/Chat.tsx')
},
output: {
entryFileNames: '[name].js',
chunkFileNames: '[name].[hash].js',
assetFileNames: '[name].[ext]'
}
}
}
})
我确保我的内容脚本是使用 Vite 捆绑的,并检查内容脚本是否正确注入到 manifest.json 中
manifest.json
{
"name": "My Extension",
"description": "Extension",
"version": "1",
"manifest_version": 3,
"minimum_chrome_version": "116",
"action": {
"default_icon": "icons/icon1.png",
"default_popup": "index.html"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["tabCapture", "offscreen", "scripting"],
"host_permissions": ["<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
您的项目似乎不允许 ES6+ 导入。尝试在 package.json 中指定
"type": "module"