import { Plugin , ResolvedConfig } from 'vite' ; import { log , addImportToCode , codeIncludesLibraryName } from './shared' ; import chalk from 'chalk' ; import defaultLibList from './resolvers' ; import * as path from 'path' ; import * as fs from 'fs' ; import { ImpConfig } from './types' ; const optionsCheck = ( options ) => { if ( options ?. libList && ! Array . isArray ( options ?. libList ) ) { log ( chalk . yellow ( `libList is Array, please check your options!` ) ) ; return false ; } return true ; } ; export default function vitePluginImp ( userConfig = { } ) { let viteConfig ; let config ; let isSourcemap = false ; const name = 'vite-plugin-imp' ; if ( ! optionsCheck ( userConfig ) ) { return { name } ; } return { name , configResolved ( resolvedConfig ) { viteConfig = resolvedConfig ; isSourcemap = ! ! viteConfig . build ?. sourcemap ; config = Object . assign ( { libList : [ ] , exclude : [ ] , ignoreStylePathNotFound : viteConfig . command === 'serve' } , userConfig ) ; const libListNameSet = new Set ( config . libList . map ( lib => lib . libName ) ) ; let defaultLibFilteredList = defaultLibList . filter ( lib => ! config . exclude ?. includes ( lib . libName ) ) ; const userPkgPath = path . resolve ( viteConfig . root , 'package.json' ) ; if ( fs . existsSync ( userPkgPath ) ) { const userPkg = require ( userPkgPath ) ; if ( userPkg ?. dependencies ) { defaultLibFilteredList = defaultLibFilteredList . filter ( item => userPkg ?. dependencies ?. [ item . libName ] ) ; } } defaultLibFilteredList . forEach ( defaultLib => { if ( ! libListNameSet . has ( defaultLib . libName ) ) { config . libList ?. push ( defaultLib ) ; libListNameSet . add ( defaultLib . libName ) ; } } ) ; } , transform ( code , id ) { if ( ! /(node_modules)/ . test ( id ) && codeIncludesLibraryName ( code , config . libList ) ) { const sourcemap = this ?. getCombinedSourcemap ( ) ; return { code : addImportToCode ( code , config , viteConfig . command , config . ignoreStylePathNotFound ) , map : isSourcemap ? sourcemap : null } ; } return { code , map : null } ; } } ; }