perf: improve package.json resolve
This commit is contained in:
parent
93763597fe
commit
cb58ef8649
|
@ -2,18 +2,18 @@ import path from 'node:path'
|
|||
import fs from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { type ChildProcess, spawn } from 'node:child_process'
|
||||
import { loadPackageData } from './utils'
|
||||
|
||||
const _require = createRequire(import.meta.url)
|
||||
|
||||
const ensureElectronEntryFile = (root = process.cwd()): void => {
|
||||
if (process.env.ELECTRON_ENTRY) return
|
||||
const pkg = path.join(root, 'package.json')
|
||||
if (fs.existsSync(pkg)) {
|
||||
const main = _require(pkg).main
|
||||
if (!main) {
|
||||
const pkg = loadPackageData()
|
||||
if (pkg) {
|
||||
if (!pkg.main) {
|
||||
throw new Error('No entry point found for electron app, please add a "main" field to package.json')
|
||||
} else {
|
||||
const entryPath = path.resolve(root, main)
|
||||
const entryPath = path.resolve(root, pkg.main)
|
||||
if (!fs.existsSync(entryPath)) {
|
||||
throw new Error(`No electron app entry file found: ${entryPath}`)
|
||||
}
|
||||
|
|
24
src/utils.ts
24
src/utils.ts
|
@ -1,6 +1,8 @@
|
|||
import { URL, URLSearchParams } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createRequire } from 'node:module'
|
||||
import { loadEnv as viteLoadEnv } from 'vite'
|
||||
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
|
@ -49,3 +51,25 @@ export function loadEnv(
|
|||
): Record<string, string> {
|
||||
return viteLoadEnv(mode, envDir, prefixes)
|
||||
}
|
||||
|
||||
interface PackageData {
|
||||
main?: string
|
||||
type?: 'module' | 'commonjs'
|
||||
}
|
||||
|
||||
let packageCached: PackageData | null = null
|
||||
|
||||
export function loadPackageData(root = process.cwd()): PackageData | null {
|
||||
if (packageCached) return packageCached
|
||||
const pkg = path.join(root, 'package.json')
|
||||
if (fs.existsSync(pkg)) {
|
||||
const _require = createRequire(import.meta.url)
|
||||
const data = _require(pkg)
|
||||
packageCached = {
|
||||
main: data.main,
|
||||
type: data.type
|
||||
}
|
||||
return packageCached
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue