import execa from "execa"; import L from "../../utils/logger"; import { probeAppType, AppType } from "../../utils/probeAppType"; import { removeLastSlash } from "../../utils/removeLastSlash"; import { findTemplateBase, writeTemplateFile } from "../../utils/template"; interface Options { pwd?: string; } const templateBase = findTemplateBase("genComponents"); async function genComponent(name: string, options?: Options): Promise { if (!options) { options = {}; } const pwd = removeLastSlash(options.pwd || "."); const [appType, upperCaseDir] = probeAppType(pwd); if (appType === AppType.UNKNOWN) { console.error("not a valid frontend project"); return; } if (appType === AppType.NATIVE) { const templatePath = `${templateBase}/native.ejs`; if (name.indexOf("/") > -1) { // nested const [screen, comp] = name.split("/"); L.info(`create a new comp ${comp} for ${screen}`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Screens" : "screens" }/${screen}`; writeTemplateFile({ outPath: `${dirPath}/${comp}.js`, templatePath, ctx: { name: comp }, }); } else if (name.indexOf("Screen") > -1) { // screen name = name.split("Screen")[0]; L.info(`create a new screen ${name} for react-native project`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Screens" : "screens" }/${name}`; execa.commandSync(`mkdir -p ${dirPath}`); writeTemplateFile({ outPath: `${dirPath}/index.js`, templatePath: `${templateBase}/native-screen.ejs`, ctx: { name }, }); } else { L.info(`create a new component ${name} for react-native project`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Components" : "components" }`; execa.commandSync(`mkdir -p ${dirPath}`); writeTemplateFile({ outPath: `${dirPath}/${name}.js`, templatePath, ctx: { name }, }); } } else if (appType === AppType.GATSBY) { const templatePath = `${templateBase}/react.ejs`; if (name.indexOf("/") > -1) { // nested const [page, comp] = name.split("/"); L.info(`create a new comp ${comp} for ${page}`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Templates" : "templates" }/${page}`; writeTemplateFile({ outPath: `${dirPath}/${comp}.js`, templatePath, ctx: { name: comp }, }); } else if (name.indexOf("Page") > -1) { name = name.split("Page")[0]; L.info(`create a new page ${name} for gatsby project`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Templates" : "templates" }/${name}`; execa.commandSync(`mkdir -p ${dirPath}`); writeTemplateFile({ outPath: `${dirPath}/index.js`, templatePath, ctx: { name }, }); } else { L.info(`create a new component ${name} for gatsby project`); const dirPath = `${pwd}/src/${ upperCaseDir ? "Components" : "components" }`; execa.commandSync(`mkdir -p ${dirPath}`); writeTemplateFile({ outPath: `${dirPath}/${name}.js`, templatePath, ctx: { name }, }); } } } export { genComponent };