Skip to content

Commit dd8627f

Browse files
committed
add root support
1 parent eddbb3b commit dd8627f

File tree

7 files changed

+57
-34
lines changed

7 files changed

+57
-34
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
"scripts": {
6161
"dev": "tsdown --watch",
6262
"build": "tsdown",
63-
"play": "cd ./playground && vite",
63+
"play": "vite",
6464
"release": "bun run format && bun run lint && bun run test && bun run build && bumpp --all",
6565
"test": "bun test",
6666
"test:dev": "bun test --watch",

src/vite/core.ts

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { bytecodePlugin } from './bytecode'
1818
import { id, log } from './constant'
1919
import electron from './electron/core'
2020
import { notBundle } from './electron/plugin'
21-
import { parseOptions } from './option'
21+
import { parseUpdaterOption } from './option'
2222
import { copyAndSkipIfExist } from './utils'
2323

2424
export interface ElectronSimpleOptions {
@@ -202,14 +202,10 @@ const defaultExternal = [
202202
export async function electronWithUpdater(
203203
options: ElectronWithUpdaterOptions,
204204
): Promise<PluginOption[] | undefined> {
205-
const pkg = await loadPackageJSON()
206-
if (!pkg || !pkg.version || !pkg.name || !pkg.main) {
207-
throw new Error('package.json not found or invalid, must contains version, name and main field')
208-
}
209-
210205
let {
211206
isBuild,
212-
external = Object.keys(pkg.dependencies || {}),
207+
root = process.cwd(),
208+
external,
213209
entry: _entry,
214210
main: _main,
215211
preload: _preload,
@@ -221,9 +217,16 @@ export async function electronWithUpdater(
221217
useNotBundle = true,
222218
} = options
223219

224-
log.info(`Clear cache files`, { timestamp: true })
220+
const pkg = await loadPackageJSON(root)
221+
if (!pkg || !pkg.version || !pkg.name || !pkg.main) {
222+
throw new Error('package.json not found or invalid, must contains version, name and main field')
223+
}
224+
225225
const isESM = pkg.type === 'module'
226-
const finalExternal = [...defaultExternal, ...(isBuild || _entry.postBuild ? [] : external)]
226+
const finalExternal = [
227+
...defaultExternal,
228+
...(isBuild || _entry.postBuild ? [] : external || Object.keys(pkg.dependencies || {})),
229+
]
227230

228231
let bytecodeOptions =
229232
typeof bytecode === 'object' ? bytecode : bytecode === true ? { enable: true } : undefined
@@ -234,15 +237,16 @@ export async function electronWithUpdater(
234237
)
235238
}
236239

237-
const { buildAsarOption, buildVersionOption, cert, entryOutDir } = await parseOptions(
240+
const { buildAsarOption, buildVersionOption, cert, entryOutDir } = await parseUpdaterOption(
238241
pkg as PKG,
239242
updater,
240243
)
241244

242-
try {
243-
fs.rmSync(buildAsarOption.electronDistPath, { recursive: true, force: true })
244-
fs.rmSync(entryOutDir, { recursive: true, force: true })
245-
} catch {}
245+
log.info(`Clear cache files`, { timestamp: true })
246+
await Promise.all([
247+
fs.promises.rm(buildAsarOption.electronDistPath, { recursive: true, force: true }),
248+
fs.promises.rm(entryOutDir, { recursive: true, force: true }),
249+
]).catch(() => {})
246250

247251
const define = {
248252
__EIU_ASAR_BASE_NAME__: JSON.stringify(path.basename(buildAsarOption.asarOutputPath)),
@@ -261,7 +265,7 @@ export async function electronWithUpdater(
261265
const _electronOptions: ElectronOptions[] = [
262266
{
263267
entry: _main.files,
264-
onstart: _main.onstart || ((args) => args.startup()),
268+
onstart: _main.onstart,
265269
vite: mergeConfig(
266270
{
267271
plugins: [
@@ -397,5 +401,5 @@ export async function electronWithUpdater(
397401
),
398402
})
399403

400-
return electron(isESM, _electronOptions)
404+
return electron(isESM, normalizePath(path.resolve(root)), _electronOptions)
401405
}

src/vite/define.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { UserConfig, UserConfigFn } from 'vite'
1+
import type { InlineConfig, UserConfig, UserConfigFn } from 'vite'
22

33
import type { ElectronWithUpdaterOptions } from './option'
44

@@ -13,7 +13,7 @@ export interface ElectronViteHelperOptions extends MakeOptional<
1313
/**
1414
* Config for renderer process
1515
*/
16-
renderer?: UserConfig
16+
renderer?: Omit<UserConfig, 'root'>
1717
}
1818

1919
/**
@@ -54,6 +54,7 @@ export function defineElectronConfig(options: ElectronViteHelperOptions): UserCo
5454
const result = options.renderer ?? {}
5555
result.plugins ??= []
5656
result.plugins.push(electronPlugin)
57+
;(result as InlineConfig).root = options.root
5758
const rendererDistPath = options.updater?.paths?.rendererDistPath
5859
if (rendererDistPath) {
5960
result.build ??= {}

src/vite/electron/core.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ export interface ElectronOptions {
2121
/**
2222
* Electron App startup function.
2323
* It will mount the Electron App child-process to `process.electronApp`.
24-
* @param argv default value `['.', '--no-sandbox']`
25-
* @param options options for `child_process.spawn`
26-
* @param customElectronPkg custom electron package name (default: 'electron')
24+
* - argv: electron startup arguments (default `['.', '--no-sandbox']`)
25+
* - options: options for `child_process.spawn`
26+
* - customElectronPkg: custom electron package name (default: `'electron'`)
2727
*/
2828
startup: (argv?: string[], options?: SpawnOptions, customElectronPkg?: string) => Promise<void>
2929
/** Reload Electron-Renderer */
@@ -37,6 +37,7 @@ export function build(isESM: boolean, options: ElectronOptions): ReturnType<type
3737

3838
export default function electron(
3939
isESM: boolean,
40+
root: string,
4041
options: ElectronOptions | ElectronOptions[],
4142
): Plugin[] {
4243
const optionsArray = Array.isArray(options) ? options : [options]
@@ -57,6 +58,13 @@ export default function electron(
5758
{
5859
name: 'vite-plugin-electron:dev',
5960
apply: 'serve',
61+
configResolved(config) {
62+
if (config.root !== root) {
63+
throw new Error(
64+
`Renderer's root (${config.root}) is not same as electron's root (${root}). Please setup \`root\` in electron plugin`,
65+
)
66+
}
67+
},
6068
configureServer(server) {
6169
server.httpServer?.once('listening', () => {
6270
Object.assign(process.env, {
@@ -72,6 +80,7 @@ export default function electron(
7280
options.vite.root ??= server.config.root
7381
options.vite.envDir ??= server.config.envDir
7482
options.vite.envPrefix ??= server.config.envPrefix
83+
const defaultArgs = [options.vite.root || '.', '--no-sandbox']
7584

7685
options.vite.build ??= {}
7786
if (!Object.keys(options.vite.build).includes('watch')) {
@@ -87,10 +96,11 @@ export default function electron(
8796
if (++closeBundleCount < entryCount) {
8897
return
8998
}
90-
9199
if (options.onstart) {
92100
options.onstart.call(this, {
93-
startup,
101+
async startup(args = defaultArgs, ...opt) {
102+
await startup(args, ...opt)
103+
},
94104
// Why not use Vite's built-in `/@vite/client` to implement Hot reload?
95105
// Because Vite only inserts `/@vite/client` into the `*.html` entry file, the preload scripts are usually a `*.js` file.
96106
// @see - https://github.com/vitejs/vite/blob/v5.2.11/packages/vite/src/node/server/middlewares/indexHtml.ts#L399
@@ -101,12 +111,12 @@ export default function electron(
101111
// For Electron apps that don't need to use the renderer process.
102112
startup.send('electron-vite&type=hot-reload')
103113
} else {
104-
startup()
114+
startup(defaultArgs)
105115
}
106116
},
107117
})
108118
} else {
109-
startup()
119+
startup(defaultArgs)
110120
}
111121
},
112122
})
@@ -143,7 +153,7 @@ export default function electron(
143153
}
144154

145155
interface StartupFn {
146-
(): Promise<void>
156+
(argv?: string[], options?: SpawnOptions, customElectronPkg?: string): Promise<void>
147157
send: (message: string) => void
148158
hookedProcessExit: boolean
149159
exit: () => Promise<void>
@@ -158,8 +168,8 @@ interface StartupFn {
158168
*/
159169
export const startup: StartupFn = async (
160170
argv = ['.', '--no-sandbox'],
161-
options?: SpawnOptions,
162-
customElectronPkg?: string,
171+
options?,
172+
customElectronPkg?,
163173
) => {
164174
const { spawn } = await import('node:child_process')
165175
const electron = await import(customElectronPkg ?? 'electron')

src/vite/option.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ export interface ElectronWithUpdaterOptions {
5050
* ```
5151
*/
5252
isBuild: boolean
53+
/**
54+
* Project root directory. Can be an absolute path, or a path relative from
55+
* the location of the config file itself.
56+
* @default process.cwd()
57+
*/
58+
root?: string
5359
/**
5460
* Whether to generate sourcemap
5561
* @default !isBuild || !!process.env.VSCODE_DEBUG
@@ -318,7 +324,7 @@ interface ParseOptionReturn {
318324
entryOutDir: string
319325
}
320326

321-
export async function parseOptions(
327+
export async function parseUpdaterOption(
322328
pkg: PKG,
323329
options: UpdaterOptions = {},
324330
): Promise<ParseOptionReturn> {

tsconfig.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
22
"extends": "@subframe7536/type-utils/tsconfig.json",
3-
"include": ["src", "tests", "playground"]
3+
"include": ["src", "tests", "playground", "vite.config.ts"]
44
}
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
import { defineElectronConfig } from '../src/vite'
1+
import { defineElectronConfig } from './src/vite'
22

33
export default defineElectronConfig({
4+
root: './playground',
45
entry: { files: ['./entry.ts', './native.ts'] },
5-
main: { files: './main.ts' },
6+
main: {
7+
files: './main.ts',
8+
},
69
// preload: { files: './preload.ts' },
7-
// todo)) new `root` in top level. create package.json if not exist
810
renderer: {},
911
updater: {},
1012
})

0 commit comments

Comments
 (0)