I'm working on a Chrome extension using Vite and React. The goal is to have it work along with my web application, and share a Supabase authentication session between the two. I'm having trouble importing the supabase-js
library in my background script.
Here is my manifest.json
:
{
"name": "Supabase Chrome Extension",
"version": "0.0.1",
"description": "",
"manifest_version": 3,
"author": "cpppatrick",
"icons": {
"16": "extension_icon16.png",
"32": "extension_icon32.png",
"48": "extension_icon48.png",
"128": "extension_icon128.png"
},
"action": {
"default_popup": "index.html",
"default_title": "Open extension"
},
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions": ["tabs", "storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
],
"externally_connectable": {
"matches": ["http://127.0.0.1:5173/*", "https://127.0.0.1:5173/*"]
}
}
Here is my vite.config.js
file:
import { defineConfig } from 'vite';
import { fileURLToPath } from 'url';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
optimizeDeps: {
include: ['@supabase/supabase-js'],
},
build: {
outDir: 'dist',
rollupOptions: {
input: {
index: './index.html',
background: fileURLToPath(new URL('./public/background.js', import.meta.url)),
},
},
// I have tried building with & without this key.
commonjsOptions: {
include: [/node_modules/],
},
},
define: {
'process.env': {},
},
});
And finally here is my background.js
file:
import { createClient } from '../node_modules/@supabase/supabase-js';
const options = {
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
storage: {
async getItem(key) {
const storage = await chrome.storage.local.get(key);
return storage?.[key];
},
async setItem(key, value) {
await chrome.storage.local.set({
[key]: JSON.parse(value),
});
},
async removeItem(key) {
await chrome.storage.local.remove(key);
},
},
},
};
export const supabase = createClient(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_ANON_KEY,
options
);
I believe it is a problem with the import
statement because when I comment it out and run npm run build
, everything builds and I don't receive any errors.
The files in this state produce the following errors, which are giving me trouble:
What I have tried so far:
- Tried using
crxjs/vite-plugin
as outlined in this answer. But it doesn't work with Vite 4 yet. - The
importScripts
approach from this answer. That gave me different errors. - Various tweaks to my
vite.config.js
file.
I don't have a lot of experience with Rollup, so I'm getting turned around trying to work with the options in my vite.config.js
file. And the error messages are not giving me a lot to work with.
TL;DR:
- How can I get imports working in my
background.js
file?