Skip to content

Commit

Permalink
fix: use tryRequire for package.json
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 3, 2021
1 parent 9493837 commit 31ab840
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import consola from 'consola'
import defu from 'defu'
import { createHooks } from 'hookable'
import prettyBytes from 'pretty-bytes'
import jiti from 'jiti'
import mkdirp from 'mkdirp'
import { dumpObject, rmdir } from './utils'
import { dumpObject, rmdir, tryRequire } from './utils'
import type { BuildContext, BuildConfig, BuildOptions } from './types'
import { validateDependencies } from './validate'
import { rollupBuild } from './builder/rollup'
Expand All @@ -19,16 +18,13 @@ export async function build (rootDir: string, stub: boolean, inputConfig: BuildC
rootDir = resolve(process.cwd(), rootDir || '.')

// Read build.config and package.json
const _require = jiti(rootDir, { interopDefault: true })
let buildConfigFile
try { buildConfigFile = _require.resolve('./build.config') } catch (e) {}
const buildConfig: BuildConfig = buildConfigFile ? _require('./build.config') : {}
const pkg = _require('./package.json')
const buildConfig: BuildConfig = tryRequire('./build.config', rootDir) || {}
const pkg = tryRequire('./package.json')

// Resolve preset
let preset = buildConfig.preset || pkg.unbuild?.preset || pkg.build?.preset || inputConfig.preset || {}
if (typeof preset === 'string') {
preset = _require(preset)
preset = tryRequire(preset)
}

// Merge options
Expand Down
11 changes: 11 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { promisify } from 'util'
import { dirname } from 'pathe'
import mkdirp from 'mkdirp'
import _rimraf from 'rimraf'
import jiti from 'jiti'

export async function ensuredir (path: string) {
await mkdirp(dirname(path))
Expand Down Expand Up @@ -31,3 +32,13 @@ export async function rmdir (dir: string) {
await fsp.unlink(dir).catch(() => { })
await rimraf(dir)
}

export function tryRequire (id: string, rootDir: string = process.cwd()) {
const _require = jiti(rootDir, { interopDefault: true })
try {
return _require(id)
} catch (_err) {
console.log(_err.code)
// Ignore
}
}

0 comments on commit 31ab840

Please sign in to comment.