Files
electron-vite/src/plugins/externalizeDeps.ts
2022-11-08 20:17:22 +08:00

45 lines
1.1 KiB
TypeScript

import path from 'node:path'
import { createRequire } from 'node:module'
import { type Plugin, mergeConfig } from 'vite'
export interface ExternalOptions {
exclude?: string[]
include?: string[]
}
/**
* Automatically externalize dependencies
*/
export function externalizeDepsPlugin(options: ExternalOptions = {}): Plugin | null {
const { exclude = [], include = [] } = options
const packagePath = path.resolve(process.cwd(), 'package.json')
const require = createRequire(import.meta.url)
const pkg = require(packagePath)
let deps = Object.keys(pkg.dependencies || {})
if (include.length) {
deps = deps.concat(include)
}
if (exclude.length) {
deps = deps.filter(dep => !exclude.includes(dep))
}
return {
name: 'vite:externalize-deps',
enforce: 'pre',
config(config): void {
const defaultConfig = {
build: {
rollupOptions: {
external: [...new Set(deps)]
}
}
}
const buildConfig = mergeConfig(defaultConfig.build, config.build || {})
config.build = buildConfig
}
}
}