I am working on a Chrome extension using Vite, React, and TypeScript. The extension includes a content script that I want to inject into active tabs. However, I am encountering the following error when the content script runs:
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]'
}
}
}
})
I ensured that my content script is bundled using Vite and checked that the content script is injected properly in the 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"]
}
]
}
1