-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.config.ts
74 lines (68 loc) · 1.84 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
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')
export default defineConfig({
build: {
minify: false,
emptyOutDir: !isdev,
target: 'node14',
lib: {
entry: {
index: 'src/index.ts',
},
formats: ['cjs', 'es'],
fileName: format => format === 'es' ? '[name].mjs' : '[name].js',
},
rollupOptions: {
external: [
'esbuild',
'vite',
...builtinModules.map(m => [m, `node:${m}`]).flat(),
...Object.keys('dependencies' in pkg ? pkg.dependencies as object : {}),
],
output: {
exports: 'named',
},
},
},
plugins: [{
name: 'generate-types',
async closeBundle() {
if (process.env.NODE_ENV === 'test') 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) {
fs.copyFileSync(path.join(types, file), path.join(dist, file))
console.log('[types]', `types/${file} -> dist/${file}`)
}
}