creat-component-cli
Background
When you want to write a new module, whether to manually create files one by one, this article will take you into script automation to create template files.
1. Installer
First we install some command-line plug-ins and develop dependencies
yarn add fs-extra chalk log-symbols -D
Copy the code
2. Set basic parameters
// Get the command line parameters to generate the corresponding file
// Get the module name entered on the command line
const moduleName = process.argv[2];
// Default template directory
const componentModulePath = path.resolve(
"./template"
); // Generate the Component in Pages
const assetsModulePath = path.resolve("./assets");
const localeModulePath = path.resolve("./locales");
// Target directory for output
const componentTargetPath = path.resolve("src/views"); // Target file corresponding to output
const assetsTargetPath = path.resolve("src/assets");
const localeTargetPath = path.resolve("src/locales");
Copy the code
3. Generate components
@param componentModulePath @Param componentTargetPath @Param moduleNme createComponent(componentModulePath, componentTargetPath, moduleName); createComponent(assetsModulePath, assetsTargetPath, moduleName); createComponent(localeModulePath, localeTargetPath, moduleName);const createComponent = (demoPath, targetpath, name) = > {
console.log(symbols.success, chalk.green("Start creating.......... Please wait a moment."));
fs.copy(demoPath, `${targetpath}/${name}`) // Copy the template file to the destination directory
.then((a)= > {
reWrite(`${targetpath}/${name}`, name); // Generate the file
console.log(symbols.success, chalk.green("Created successfully"));
})
.catch(err= > {
console.log(symbols.error, chalk.red("Create failed", err));
});
const reWrite = (path, name) = > {
const files = fs.readdirSync(path);
files.forEach(file= > {
const fileName = `${path}/${file}`;
if (fs.statSync(fileName).isFile()) {
const content = fs.readFileSync(fileName).toString();
// Create sub-component XXX/yy, intercept YY
const demoName = name.split("/").reverse()[0];
// Truncate the component name -, then write the component name with a big hump
const result = content.replace(/template/g, stringToCamel(demoName));
fs.writeFileSync(fileName, result);
} else{ reWrite(fileName, name); }}); };// Convert the string to a big hump
const stringToCamel = str= > {
let temp = str.split("-");
for (let i = 0; i < temp.length; i++) {
temp[i] = temp[i][0].toUpperCase() + temp[i].slice(1);
}
return temp.join("");
};
};
Copy the code
Github Portal github.com/promotion-x…