Skip to content

Instantly share code, notes, and snippets.

@jacksteamdev
Created November 2, 2021 16:23
Show Gist options
  • Save jacksteamdev/41de7f6d010ebe2f4bd22cad800d9380 to your computer and use it in GitHub Desktop.
Save jacksteamdev/41de7f6d010ebe2f4bd22cad800d9380 to your computer and use it in GitHub Desktop.
vite-plugin-crx-react
import react from '@vitejs/plugin-react'
import type { RPCEPlugin } from 'rollup-plugin-chrome-extension'
import type {
HmrOptions,
PluginOption,
ViteDevServer,
} from 'vite'
export default function createPlugins(
...args: Parameters<typeof react>
) {
const [babel, refresh, jsx] = react(...args)
return [
createBabelPlugin(babel),
createRefreshPlugin(refresh),
jsx,
] as PluginOption[]
}
const preambleId = '/@react-refresh-preamble'
function createBabelPlugin(vitePlugin: PluginOption) {
if (!vitePlugin) return null
const crxPlugin: RPCEPlugin = {
name: 'crx:react-babel',
transform(...args) {
const [, id] = args
const params = new URLSearchParams(
id.split('?').slice(1).join('?'),
)
if (params.has('crx')) return null
return vitePlugin.transform?.call(this, ...args)
},
}
return { ...vitePlugin, ...crxPlugin } as PluginOption
}
function createRefreshPlugin(vitePlugin: PluginOption) {
if (!vitePlugin) return null
let server: ViteDevServer | undefined
const crxPlugin: RPCEPlugin = {
name: 'crx:react-refresh',
config(config) {
config.server = config.server ?? {}
if (config.server?.hmr === false) return config
const hmr =
typeof config.server.hmr === 'object'
? config.server.hmr
: ({} as HmrOptions)
hmr.host = hmr.host ?? 'localhost'
config.server.hmr = hmr
return config
},
configureServer(s) {
server = s
},
resolveId(...args) {
const [id] = args
if (id === preambleId) return id
return vitePlugin.resolveId?.call(this, ...args)
},
load(...args) {
const [id] = args
if (id === preambleId)
return react.preambleCode.replace('__BASE__', '/')
return vitePlugin.load?.call(this, ...args)
},
transformIndexHtml(source) {
if (server)
return [
{
tag: 'script',
attrs: {
type: 'module',
src: preambleId,
},
},
]
return []
},
}
return { ...vitePlugin, ...crxPlugin } as PluginOption
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment