-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.ts
More file actions
382 lines (342 loc) · 11.4 KB
/
index.ts
File metadata and controls
382 lines (342 loc) · 11.4 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import fs from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import prompts from 'prompts'
type Framework = 'vue' | 'react' | 'vanilla'
/**
* @see https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color
* @see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
*/
export const COLOURS = {
$: (c: number) => (str: string) => `\x1b[${c}m` + str + '\x1b[0m',
gary: (str: string) => COLOURS.$(90)(str),
cyan: (str: string) => COLOURS.$(36)(str),
yellow: (str: string) => COLOURS.$(33)(str),
green: (str: string) => COLOURS.$(32)(str),
red: (str: string) => COLOURS.$(31)(str),
}
const cwd = process.cwd()
const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const argTargetDir = process.argv.slice(2).join(' ')
const defaultTargetDir = 'electron-vite-project'
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
async function init() {
let template: prompts.Answers<'projectName' | 'overwrite' | 'packageName' | 'framework'>
let targetDir = argTargetDir ?? defaultTargetDir
const getProjectName = () => (targetDir === '.' ? path.basename(path.resolve()) : targetDir)
try {
template = await prompts(
[
{
type: () => (argTargetDir ? null : 'text'),
name: 'projectName',
message: 'Project name:',
initial: defaultTargetDir,
onState: (state) => {
targetDir = state?.value.trim().replace(/\/+$/g, '') ?? defaultTargetDir
},
},
{
type: () =>
!fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm',
name: 'overwrite',
message: () =>
(targetDir === '.'
? 'Current directory'
: `Target directory "${targetDir}"`) +
` is not empty. Remove existing files and continue?`,
},
{
type: (_, { overwrite }: { overwrite?: boolean }) => {
if (overwrite === false) {
throw new Error(COLOURS.red('✖') + ' Operation cancelled')
}
return null
},
name: 'overwriteChecker',
},
{
type: () => (isValidPackageName(getProjectName()) ? null : 'text'),
name: 'packageName',
message: 'Package name:',
initial: () => toValidPackageName(getProjectName()),
validate: (dir) => isValidPackageName(dir) || 'Invalid package.json name',
},
{
type: 'select',
name: 'framework',
message: 'Project template:',
choices: [
{
title: 'Vue',
value: 'vue',
},
{
title: 'React',
value: 'react',
},
{
title: 'Vanilla',
value: 'vanilla',
}
]
}
],
{
onCancel: () => {
throw new Error(`${COLOURS.red('✖')} Operation cancelled`)
},
},
)
} catch (cancelled: any) {
console.log(cancelled.message)
return
}
// User choice associated with prompts
const { overwrite, framework, packageName } = template
const root = path.join(cwd, targetDir)
// https://github.com/vitejs/vite/pull/12390#issuecomment-1465457917
if (overwrite) {
emptyDir(root)
} else if (!fs.existsSync(root)) {
fs.mkdirSync(root, { recursive: true })
}
console.log(`\nScaffolding project in ${root}...`)
const templateDir = path.resolve(__dirname, '..', `template-${framework}-ts`)
const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent)
const pkgManager = pkgInfo ? pkgInfo.name : 'npm'
const write = (file: string, content?: string) => {
const targetPath = path.join(root, renameFiles[file] ?? file)
if (content) {
fs.writeFileSync(targetPath, content)
} else {
copy(path.join(templateDir, file), targetPath)
}
}
const files = fs.readdirSync(templateDir)
for (const file of files.filter((f) => f !== 'package.json')) {
write(file)
}
const pkg = JSON.parse(
fs.readFileSync(path.join(templateDir, 'package.json'), 'utf-8'),
)
pkg.name = packageName || getProjectName()
write('package.json', JSON.stringify(pkg, null, 2) + '\n')
// Mixing in Electron code snippets
setupElectron(root, framework)
console.log(`\nDone. Now run:\n`)
const cdProjectName = path.relative(cwd, root)
if (root !== cwd) {
console.log(` cd ${cdProjectName.includes(' ') ? `"${cdProjectName}"` : cdProjectName}`)
}
switch (pkgManager) {
case 'yarn':
console.log(' yarn')
console.log(' yarn dev')
break
default:
console.log(` ${pkgManager} install`)
console.log(` ${pkgManager} run dev`)
break
}
console.log()
}
function isEmpty(path: string) {
const files = fs.readdirSync(path)
return files.length === 0 || (files.length === 1 && files[0] === '.git')
}
function emptyDir(dir: string) {
if (!fs.existsSync(dir)) {
return
}
for (const file of fs.readdirSync(dir)) {
if (file === '.git') {
continue
}
fs.rmSync(path.resolve(dir, file), { recursive: true, force: true })
}
}
function isValidPackageName(projectName: string) {
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(projectName)
}
function toValidPackageName(projectName: string) {
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z\d\-~]+/g, '-')
}
function copy(src: string, dest: string) {
const stat = fs.statSync(src)
if (stat.isDirectory()) {
copyDir(src, dest)
} else {
fs.copyFileSync(src, dest)
}
}
function copyDir(srcDir: string, destDir: string) {
fs.mkdirSync(destDir, { recursive: true })
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file)
const destFile = path.resolve(destDir, file)
copy(srcFile, destFile)
}
}
function editFile(file: string, callback: (content: string) => string) {
const content = fs.readFileSync(file, 'utf-8')
fs.writeFileSync(file, callback(content), 'utf-8')
}
function pkgFromUserAgent(userAgent: string | undefined) {
if (!userAgent) return undefined
const pkgSpec = userAgent.split(' ')[0]
const pkgSpecArr = pkgSpec.split('/')
return {
name: pkgSpecArr[0],
version: pkgSpecArr[1],
}
}
function setupElectron(root: string, framework: Framework) {
const sourceDir = path.resolve(__dirname, '..', 'electron')
const electronDir = path.join(root, 'electron')
const publicDir = path.join(root, 'public')
const pkg = require('../electron/package.json')
fs.mkdirSync(electronDir, { recursive: true })
// Electron files
for (const name of [
'electron-env.d.ts',
'main.ts',
'preload.ts',
]) {
fs.copyFileSync(path.join(sourceDir, name), path.join(electronDir, name))
}
for (const name of [
'electron-vite.animate.svg',
'electron-vite.svg',
]) {
fs.copyFileSync(path.join(sourceDir, name), path.join(publicDir, name))
}
for (const name of [
'electron-builder.json5',
]) {
fs.copyFileSync(path.join(sourceDir, name), path.join(root, name))
}
// package.json
editFile(path.join(root, 'package.json'), content => {
const json = JSON.parse(content)
json.main = 'dist-electron/main.js'
json.scripts.build = `${json.scripts.build} && electron-builder`
json.devDependencies.electron = pkg.devDependencies.electron
json.devDependencies['electron-builder'] = pkg.devDependencies['electron-builder']
json.devDependencies['vite-plugin-electron'] = pkg.devDependencies['vite-plugin-electron']
json.devDependencies['vite-plugin-electron-renderer'] = pkg.devDependencies['vite-plugin-electron-renderer']
return JSON.stringify(json, null, 2) + '\n'
})
// main.ts
const snippets = (indent = 0) => `
// Use contextBridge
window.ipcRenderer.on('main-process-message', (_event, message) => {
console.log(message)
})
`.trim()
.split('\n')
.map(line => line ? ' '.repeat(indent) + line : line)
.join('\n')
if (framework === 'vue') {
editFile(path.join(root, 'src/main.ts'), content =>
content.replace(`mount('#app')`, `mount('#app').$nextTick(() => {\n${snippets(2)}\n})`)
)
} else if (framework === 'react') {
editFile(path.join(root, 'src/main.tsx'), content => `${content}\n${snippets()}\n`)
} else if (framework === 'vanilla') {
editFile(path.join(root, 'src/main.ts'), content => `${content}\n${snippets()}\n`)
}
// vite.config.ts
const electronPlugin = `electron({
main: {
// Shortcut of \`build.lib.entry\`.
entry: 'electron/main.ts',
},
preload: {
// Shortcut of \`build.rollupOptions.input\`.
// Preload scripts may contain Web assets, so use the \`build.rollupOptions.input\` instead \`build.lib.entry\`.
input: path.join(__dirname, 'electron/preload.ts'),
},
// Polyfill the Electron and Node.js API for Renderer process.
// If you want use Node.js in Renderer process, the \`nodeIntegration\` needs to be enabled in the Main process.
// See 👉 https://github.com/electron-vite/vite-plugin-electron-renderer
renderer: process.env.NODE_ENV === 'test'
// https://github.com/electron-vite/vite-plugin-electron-renderer/issues/78#issuecomment-2053600808
? undefined
: {},
})`
if (framework === 'vue' || framework === 'react') {
editFile(path.join(root, 'vite.config.ts'), content =>
content
.split('\n')
.map(line => line.includes("import { defineConfig } from 'vite'")
? `${line}
import path from 'node:path'
import electron from 'vite-plugin-electron/simple'`
: line)
.map(line => line.trimStart().startsWith('plugins')
? ` plugins: [
${framework}(),
${electronPlugin},
],`
: line)
.join('\n')
)
} else {
fs.writeFileSync(
path.join(root, 'vite.config.ts'),
`
import { defineConfig } from 'vite'
import path from 'node:path'
import electron from 'vite-plugin-electron/simple'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
${electronPlugin},
],
})
`.trimStart()
)
}
// tsconfig.json
editFile(path.join(root, 'tsconfig.json'), content =>
content
.split('\n')
.map(line => line.trimStart().startsWith('"include"') ? line.replace(']', ', "electron"]') : line)
.join('\n')
)
// .gitignore
editFile(path.join(root, '.gitignore'), content =>
content
.split('\n')
.map(line => line === 'dist-ssr' ? `${line}\ndist-electron\nrelease` : line)
.join('\n')
)
// site 👉 https://electron-vite.github.io
// logo 👉 electron-vite.svg
if (framework === 'vue') {
editFile(path.join(root, 'src/App.vue'), content => content
.replace('https://vitejs.dev', 'https://electron-vite.github.io')
.replace('/vite.svg', '/electron-vite.svg'))
} else if (framework === 'react') {
editFile(path.join(root, 'src/App.tsx'), content => content
.replace('https://vitejs.dev', 'https://electron-vite.github.io')
.replace('/vite.svg', '/electron-vite.animate.svg'))
} else if (framework === 'vanilla') {
editFile(path.join(root, 'src/main.ts'), content => content
.replace('https://vitejs.dev', 'https://electron-vite.github.io')
.replace('/vite.svg', '/electron-vite.svg'))
}
}
init().catch((e) => {
console.error(e)
})