google-chrome-extensionvitebundling-and-minificationrollupjsesbuild

Running multiple Vite configs in watch mode


I am trying to build chrome extension and use Vite. I am able to build the project, but I don't know how to run it in watch mode.

package.json

{
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "run-p dev:main dev:background",
    "dev:main": "vite build --watch",
    "dev:background": "vite build --watch --config vite.chrome.background.config.ts",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "build:background:chrome": "vite build --config vite.chrome.background.config.ts",
    "build-all": "run-s build build:background:chrome",
    "tsc": "tsc"
  },
  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@types/chrome": "0.0.228",
    "@types/node": "18.15.11",
    "@types/react": "18.0.33",
    "@types/react-dom": "18.0.11",
    "@typescript-eslint/eslint-plugin": "5.57.1",
    "@typescript-eslint/parser": "5.57.1",
    "@vitejs/plugin-react": "2.2.0",
    "eslint": "8.37.0",
    "eslint-config-prettier": "8.8.0",
    "eslint-plugin-import": "2.27.5",
    "npm-run-all": "4.1.5",
    "prettier": "2.8.7",
    "typescript": "5.0.4",
    "vite": "3.2.0"
  },
  "packageManager": "yarn@3.5.0",
  "engines": {
    "node": "18.15.0",
    "npm": "please-use-yarn",
    "yarn": "3.5.0"
  }
}

vite.config.js

import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    sourcemap: true,
    rollupOptions: {
      input: {
        index: './window-index.html',
        popup: './popup-index.html',
      },
    },
  },
})

vite.chrome.background.config.ts

import { resolve } from 'path'

import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    emptyOutDir: false,
    outDir: resolve(__dirname, 'dist'),
    sourcemap: true,
    lib: {
      formats: ['iife'],
      entry: resolve(__dirname, './src/background/background.ts'),
      name: 'background',
    },
    rollupOptions: {
      output: {
        entryFileNames: 'background.global.js',
        extend: true,
      },
    },
  },
})

If I run yarn run dev, project is built without any issues.

When I make a change in popup-index.html or window-index.html, the change is reflected, but only vite.config.js is rebuilt. The another config vite.chrome.background.config.ts is not rebuilt and dist directory is missing background.global.js.


Solution

  • I solved this by using @crxjs/vite-plugin