forked from electron-vite/vite-plugin-electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.config.ts
91 lines (83 loc) · 2.39 KB
/
vite.config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import fs from 'node:fs'
import path from 'node:path'
import { spawn } from 'node:child_process'
import { builtinModules } from 'node:module'
import { defineConfig } from 'vite'
import pkg from './package.json'
const isdev = process.argv.slice(2).includes('--watch')
const istest = process.env.NODE_ENV === 'test'
export default defineConfig(() => {
if (!isdev && !istest) {
for (const dir of ['dist', 'plugin']) {
fs.rmSync(path.join(__dirname, dir), { recursive: true, force: true })
}
}
return {
build: {
minify: false,
emptyOutDir: false,
outDir: 'dist',
lib: {
entry: {
index: 'src/index.ts',
plugin: 'src/plugin.ts',
simple: 'src/simple.ts',
},
formats: ['cjs', 'es'],
fileName: format => format === 'es' ? '[name].mjs' : '[name].js',
},
rollupOptions: {
external: [
'vite',
'electron',
...builtinModules,
...builtinModules.map(m => `node:${m}`),
...Object.keys('dependencies' in pkg ? pkg.dependencies as object : {}),
...Object.keys('peerDependencies' in pkg ? pkg.peerDependencies as object : {}),
],
output: {
exports: 'named',
},
},
},
plugins: [{
name: 'generate-types',
async closeBundle() {
if (istest) return
removeTypes()
await generateTypes()
moveTypesToDist()
removeTypes()
},
}],
}
})
function removeTypes() {
fs.rmSync(path.join(__dirname, 'types'), { recursive: true, force: true })
}
function generateTypes() {
return new Promise(resolve => {
const cp = spawn(
process.platform === 'win32' ? 'npm.cmd' : 'npm',
['run', 'types'],
{ stdio: 'inherit' },
)
cp.on('exit', code => {
!code && console.log('[types]', 'declaration generated')
resolve(code)
})
cp.on('error', process.exit)
})
}
function moveTypesToDist() {
const types = path.join(__dirname, 'types')
const dist = path.join(__dirname, 'dist')
const files = fs.readdirSync(types).filter(n => n.endsWith('.d.ts'))
for (const file of files) {
const from = path.join(types, file)
const to = path.join(dist, file)
fs.writeFileSync(to, fs.readFileSync(from, 'utf8'))
const cwd = process.cwd()
console.log('[types]', `${path.relative(cwd, from)} -> ${path.relative(cwd, to)}`)
}
}