import { join } from 'path' ; import { existsSync , promises as fs } from 'fs' ; import _debug from 'debug' ; import type { Plugin } from 'vite' ; const debug = _debug ( 'vite-plugin-package-config' ) ; export interface Options { default packageJsonPath ? : string ; default field ? : string ; } export interface VitePluginPackageConfigPlugin extends Plugin { api : { options : { packageJsonPath : string ; field : string ; } ; } ; } function VitePluginPackageConfig ( options = { } ) { const { packageJsonPath = join ( process . cwd ( ) , 'package.json' ) , field = 'vite' , } = options ; return { name : 'vite-plugin-package-config' , async config ( ) { if ( ! existsSync ( packageJsonPath ) ) { debug ( 'package.json not found at %s' , packageJsonPath ) ; return ; } debug ( 'loading package.json at %s' , packageJsonPath ) ; try { const packageJson = JSON . parse ( await fs . readFile ( packageJsonPath , 'utf-8' ) ) ; const extend = packageJson [ field ] ; if ( ! extend ) { debug ( 'no %s field found in package.json, skip' , field ) ; return ; } debug ( 'merging config with %o' , extend ) ; return extend ; } catch ( e ) { debug ( 'parse error: %o' , e ) ; debug ( 'error on loading package.json at %s, skip' , packageJsonPath ) ; } } , api : { options : { packageJsonPath , field , } , } , } ; } export default VitePluginPackageConfig ;