generated from antfu-collective/vitesse-webext
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.ts
234 lines (222 loc) · 6.68 KB
/
build.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/* eslint-disable no-console */
import type { InlineConfig } from 'vite'
import { mergeConfig, build as viteBuild } from 'vite'
import WindiCSS from 'vite-plugin-windicss'
import chokidar from 'chokidar'
import fs from 'fs-extra'
import { blue, cyan, green, red, yellow } from 'kolorist'
import type { BuildCliOptions } from 'shim'
import { getManifest } from './src/manifest'
import { isDev as _isDev, log, parseArgs, port, r } from './scripts/utils'
import { sharedConfig } from './vite.config'
import windiConfig from './windi.config'
import packageJson from './package.json'
/**
* If target is an array, because of the building is common and the only difference between firefox(mv2) and chrome(mv3),
* so we need create a common directory for building, and then copy it to different target directory.
*/
const { target, prod, name } = parseArgs<BuildCliOptions>({
maps: {
t: 'target',
p: 'prod',
n: 'name',
},
serialize: (value: any, key) => {
value = value.split(',')
return value.length === 1 ? ['target', 'name'].includes(key) ? value : value[0] : value
},
})
const isDev = typeof prod !== 'undefined' ? !prod : _isDev
const logError = (err: string) => {
throw new Error(red(err))
}
function validBefore() {
if (!target)
logError(`Please specify target, like: ${green('esno build.ts -t firefox')}`)
const invalidTarget = target.filter(t => !['chromium', 'firefox'].includes(t))
if (invalidTarget.length)
logError(`Invalid target: ${red(invalidTarget.join(', '))}`)
if (name && name.length !== target.length)
logError(`The length of target(t) and name(n) must be equal, but got ${target.length} target and ${name.length} name`)
}
// Check
validBefore()
const destName = name || target
const config: InlineConfig = {
...sharedConfig,
build: {
watch: isDev ? {} : undefined,
cssCodeSplit: false,
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
minify: isDev ? 'esbuild' : 'terser',
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
compress: {
// 生产环境时移除console
drop_console: true,
drop_debugger: true,
},
},
},
plugins: [
...sharedConfig.plugins!,
// https://github.com/antfu/vite-plugin-windicss
WindiCSS({
config: {
...windiConfig,
// disable preflight to avoid css population
preflight: false,
},
}),
],
}
const logPlugin = (title: string, message: string) => ({
name: title,
enforce: 'pre',
buildStart: () => log(title, message),
})
const copyPlugin = (title: string, dir: string) => ({
name: `copy-assets-${title.toLowerCase()}`,
writeBundle(_: any, assets: object) {
const files = Object.keys(assets)
target.map(async(t: string) => {
files.map(async(file: string) => {
await fs.copy(
r(`extension/__COMMON__/dist/${dir}/${file}`),
r(`extension/${t}/dist/${dir}/${file}`),
{ overwrite: true },
)
log(title, `Copied to ${green(r(`extension/${t}/dist/${dir}/${file}`))}`)
})
})
},
})
// Copy assets to dist folder
async function copyAssets() {
return Promise.all(destName.map(async(name: string) => {
const dest = r(`extension/${name}/assets`)
const exists = await fs.pathExists(dest)
if (exists) {
log('PRE', `Assets exists at ${green(dest)}`)
return
}
await fs.copy(r('extension/assets'), dest)
log('PRE', `Copied assets done at ${green(dest)}`)
}))
}
// Clear dist folder
async function clearDestination() {
return Promise.all(destName.map(async(name: string) => {
await fs.remove(r(`extension/${name}/dist`))
log('PRE', `Cleared ${yellow(r(`extension/${name}/dist`))}`)
await fs.remove(r(`extension/${name}/manifest.json`))
log('PRE', `Cleared ${yellow(r(`extension/${name}/manifest.json`))}`)
}))
}
// Create manifest.json
async function writeManifest() {
return Promise.all(target.map(async(t: string, i: number) => {
const dest = r(`extension/${destName[i]}/manifest.json`)
await fs.writeJSON(dest, await getManifest(t), { spaces: 2 })
log('PRE', `Wrote ${cyan(t)} manifest at ${green(dest)}`)
}))
}
// Build popup
async function buildPopup() {
log()
const dest = r(`extension/${destName.length > 1 ? '__COMMON__' : destName[0]}/dist`)
await viteBuild(mergeConfig(config, {
base: '/dist/',
// For right reference assets in popup development mode
server: {
port,
hmr: {
host: 'localhost',
},
},
build: {
outDir: dest,
rollupOptions: {
input: {
popup: r('src/popup/index.html'),
},
},
},
plugins: destName.length > 1 && [
logPlugin('POPUP', 'Building popup'),
copyPlugin('POPUP', '/'),
],
}))
}
// Build background scripts
async function buildBackground() {
log()
const dest = r(`extension/${destName.length > 1 ? '__COMMON__' : destName[0]}/dist/background`)
await viteBuild(mergeConfig(config, {
build: {
outDir: dest,
lib: {
entry: r('src/background/main.ts'),
formats: ['cjs'],
},
rollupOptions: {
output: {
entryFileNames: 'background.js',
extend: true,
},
},
},
plugins: destName.length > 1 && [
logPlugin('BACKGROUND', 'Building background.js'),
copyPlugin('BACKGROUND', 'background'),
],
}))
}
// Build content scripts
async function buildContent() {
log()
const dest = r(`extension/${destName.length > 1 ? '__COMMON__' : destName[0]}/dist/contentScripts`)
await viteBuild(mergeConfig(config, {
build: {
outDir: dest,
lib: {
entry: r('src/contentScripts/index.ts'),
name: packageJson.name,
formats: ['iife'],
},
rollupOptions: {
output: {
entryFileNames: 'index.global.js',
extend: true,
},
},
},
plugins: destName.length > 1 && [
logPlugin('CONTENT SCRIPTS', 'Building content scripts'),
copyPlugin('CONTENT SCRIPTS', 'contentScripts'),
],
}))
}
async function build() {
log('INFO', `Get ${target.length} targets - ${blue(target.join(', '))}`)
log('INFO', `Get ${destName.length} destName, it will gererated in:\n${blue(destName.map(n => r(`extension/${n}`)).join('\n'))}`)
destName.forEach(async(name: string) => {
await fs.ensureDir(r(`extension/${name}`))
})
log()
await clearDestination()
await writeManifest()
await copyAssets()
await buildPopup()
await buildBackground()
await buildContent()
}
build()
if (isDev) {
chokidar.watch([r('src/manifest.ts'), r('package.json')])
.on('change', async() => {
await writeManifest()
})
}