Build a Chrome Extension with Vue/Vite
At the time of writing this note, official Vue has switched to Vite, which is a much faster alternative of original Vue CLI.
See Vite Note for more details.
See Sample Code
Vite
Let’s suppose you want to build 2 diffrent pages, one for popup and one for options.
Procedures
npm init vue@latest- Select the components you need
npm install- Copy
index.htmland name the new filepopup.html, rename./src/main.tstopopup.ts.- Within
popup.html, replace thesrcof<script type="module" src="/src/main.ts"></script>with/src/popup.ts
- Within
- Make a copy of
popup.htmland./src/popup.ts, call themoptions.htmland./src/options.ts- Within
options.html, replace thesrcwith./src/options.ts
- Within
- Rename
./src/App.vueto./src/Popup.vue. Make a copy of it and name it./src/Options.vue./src/options.tsand./src/popup.tswill be the entrypoint when building the 2 pages./src/Popup.vueand./src/Options.vuewill be the 2 pages themselves
- In
vite.config.ts, add the following todefineConfig
import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
const root = resolve(__dirname, 'src');
const outDir = resolve(__dirname, 'dist');
const publicDir = resolve(__dirname, 'public')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
publicDir,
root,
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
build: {
outDir,
emptyOutDir: true,
rollupOptions: {
input: {
popup: resolve(root, 'index.html'),
options: resolve(root, 'pages/options/index.html')
}
}
}
})- Now, if you run
npm run build, the dist folder will containoptions.htmlandpopup.html - Note that the
index.htmlis not deleted. It’s used for development server.- Toggle the
srcattribute between/src/popup.tsand/src/options.tsto decide which page you want to develop. - Another option is to use a config file to specify which entrypoint html file to use.
- Toggle the
Sample Code
See chrome-ext-vue3-ts for sample code.
Check different branches. Both original Vue and Vite examples are supplied.