|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import fs from "fs"; |
|
|
import path from "path"; |
|
|
import chalk from "chalk"; |
|
|
import generateComponentSrc from "./templates/component-src"; |
|
|
|
|
|
const componentRootPath = "src/components"; |
|
|
|
|
|
|
|
|
|
|
|
const nameParamFormat = new RegExp(/^((?:[\w-]+\/)*)([A-Z][\w-]+)$/); |
|
|
const componentArg = process.argv[2]; |
|
|
|
|
|
if (!componentArg) { |
|
|
throw "Component name was not passed. Usage: jss scaffold <ComponentName>"; |
|
|
} |
|
|
|
|
|
const regExResult = nameParamFormat.exec(componentArg); |
|
|
|
|
|
if (regExResult === null) { |
|
|
throw `Component name should start with an uppercase letter and contain only letters, numbers, |
|
|
dashes, or underscores. If specifying a path, it must be relative to src/components`; |
|
|
} |
|
|
|
|
|
const componentPath = regExResult[1]; |
|
|
const componentName = regExResult[2]; |
|
|
const filename = `${componentName}.tsx`; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function editLineEndings(content: string) { |
|
|
return content.replace(/\r|\n/gm, "\r\n"); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function scaffoldFile( |
|
|
rootPath: string, |
|
|
fileContent: string, |
|
|
filename: string, |
|
|
): string | null { |
|
|
const outputDir = path.join(rootPath, componentPath); |
|
|
const outputFile = path.join(outputDir, filename); |
|
|
|
|
|
if (fs.existsSync(outputFile)) { |
|
|
console.log(chalk.red(`Skipping creating ${outputFile}; already exists.`)); |
|
|
return null; |
|
|
} |
|
|
|
|
|
fs.mkdirSync(outputDir, { recursive: true }); |
|
|
fs.writeFileSync(outputFile, editLineEndings(fileContent), "utf8"); |
|
|
console.log(chalk.green(`File ${outputFile} has been scaffolded.`)); |
|
|
return outputFile; |
|
|
} |
|
|
|
|
|
const componentOutputPath = scaffoldFile( |
|
|
componentRootPath, |
|
|
generateComponentSrc(componentName), |
|
|
filename, |
|
|
); |
|
|
|
|
|
console.log( |
|
|
chalk.green(` |
|
|
Scaffolding of ${componentName} complete. |
|
|
Next steps:`), |
|
|
); |
|
|
|
|
|
if (componentOutputPath) { |
|
|
console.log( |
|
|
`* Implement the React component in ${chalk.green(componentOutputPath)}`, |
|
|
); |
|
|
} |
|
|
|