import path from 'path' import ejs from 'ejs' import { ConeScaffoldProps, PkgJsonPatch, Obj, ComponentFileProcessor, } from '../type' import { formatJson, formatCode } from '../prettier' import { isExtJs, isExtTs } from '../js' import { processCss, isExtCss } from '../css' import { processJs } from './js' import { PKG_JSON_FILE_NAME } from '../package-json' import { CONE_CONFIG_FILE_NAME } from '../project/cone-config' import { BUILD_JSON_FILE_NAME } from '../project/build-json' import { updateConeComponentConfig } from './cone-config' import { updateComponentBuildJson } from './build-json' import { updateComponentPackageJson } from './package-json' const processorMap: Record = { [CONE_CONFIG_FILE_NAME]: updateConeComponentConfig, [BUILD_JSON_FILE_NAME]: updateComponentBuildJson, [PKG_JSON_FILE_NAME]: updateComponentPackageJson, } export async function postProcessComponentFile({ srcDir, destDir, filepath, str, props, pkgJsonPatch, }: { srcDir: string destDir: string filepath: string str: string | Obj props: ConeScaffoldProps pkgJsonPatch?: PkgJsonPatch }): Promise { const absFilePath = path.resolve(srcDir, filepath) if (typeof str === 'object') { str = JSON.stringify(str, null, 2) + '\n' } // ejs render try { str = ejs.render(str, props, { filename: filepath }) } catch (err) { // ignore render err } // extra process const fn = processorMap[filepath] if (fn) { let obj = {} const isJson = filepath.endsWith('.json') if (isJson) { obj = JSON.parse(str) as Obj } const rtn = await fn({ srcDir, destDir, filepath, str, obj, props, pkgJsonPatch, }) if (typeof rtn === 'string') { str = rtn } else { str = await formatJson({ filepath: absFilePath, obj: rtn }) } } // 处理 js if (isExtJs(filepath) || isExtTs(filepath)) { str = processJs({ str, filepath, props, }) str = await formatCode({ filepath: absFilePath, str }) } return str }