開發(fā)的時候,比如在android mvp或者React Native里面基于Redux架構(gòu),在編寫一個頁面時經(jīng)常會需要創(chuàng)建類似的固定幾個文件,我們可以通過nodejs來協(xié)助我們完成模板文件的創(chuàng)建。
以下介紹這個npm 包項目的簡單示例創(chuàng)建過程:
1:目錄結(jié)構(gòu)

2:package.json文件說明(該文件可通過命令npm init生成):
`{`
`"name"``: ``"template-create-file"``,`
`"version"``: ``"1.0.0"``,`
`"description"``: ``"template file create"``,`
`"main"``: ``"index.js"``,`
`"scripts"``: {`
`"test"``: ``"echo \"Error: no test specified\" && exit 1"``,`
`"createFile"``: ``"node createFile.js"``,`
`"insertProps"``: ``"node insertProps.js"`
`},`
`"bin"``: {`
`"create-file"``: ``"createFile.js"``,`
`"insert-props"``: ``"insertProps.js"`
`},`
`"keywords"``: [],`
`"author"``: ``"leach chen"``,`
`"license"``: ``"ISC"``,`
`"publishConfig"``: {`
`"registry"``: ``"xxx發(fā)布的倉庫地址"`
`}`
`}`
name:項目包名,如安裝時 npm install template-create-file
version:版本,每次發(fā)布新包時需要提升版本號
main:指定項目入口文件
scripts:指定可以執(zhí)行的腳本命令,調(diào)試時可以通過npm run test、npm run createFile、npm run insertProps方式執(zhí)行指定文件。
bin:該配置比較重要,當(dāng)你通過npm install -g template-create-file 安裝該包后,就可以在命令行里通過create-file、insert-props全局執(zhí)命令

publishConfig:指定要發(fā)布的倉庫
3:創(chuàng)建模板文件代碼(createFile.js):
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const args = process.argv.splice(2);
const componentName = args[0]; // 獲取到組件名
const templateType = args[1] //模板類型
const filePath = args[2]; // 獲取到文件存儲路徑
let root = process.cwd(); //獲取當(dāng)前路徑
let replaceStr = "" //要全局替換的字符串
console.log(args)
run()
function run() {
if(!componentName) //組件名稱沒有輸入
{
showHelp()
return
}
if(filePath)//如果自定義路徑存在
{
root = filePath
}
if(args[0] == "help" || args[0] == "-help" || args[0] == "--help") { //顯示命令列表
showHelp()
}if(args[0] == "list") { //顯示模板列表
showTemplateList()
}else{
switch (templateType) {
case "1":
createTemplate1()
break
default:
createTemplate1()
}
}
}
function createTemplate1() {
replaceStr= "TemplateDemo"
createFile("./Template/Template1/TemplateDemoPage.tsx")
createFile("./Template/Template1/TemplateDemoView.tsx")
createFile("./Template/Template1/TemplateDemoTypes.ts")
createFile("./Template/Template1/TemplateDemoAction.ts")
createFile("./Template/Template1/TemplateDemoReducer.ts")
}
function showHelp() {
console.log("*****************************************************************************************");
console.log(" you can use below command:");
console.log(" 1. 'create-file help'");
console.log(" 2. 'create-file list',show contains template list");
console.log(" 3. 'create-file ModuleName',for example(react-create TestModule)");
console.log(" 4. 'create-file ModuleName Type',for example(react-create TestModule 1),type value is 1,2,3...,you can use 'react-create list' show template list");
console.log(" 5. 'create-file ModuleName Type FilePath',for example(react-native TestModule 1 D:\\Prj\\TestProject)");
console.log("*****************************************************************************************");
}
function showTemplateList() {
console.log("*****************************************************************************************");
console.log(" Template List:");
console.log(" 1. TemplateDemoPage.tsx、TemplateDemoView.ts、TemplateDemoTypes.ts、TemplateDemoAction.ts、TemplateDemoReducer.ts");
console.log("*****************************************************************************************");
}
function createFile(templatePath)
{
// 讀取模板文件,并修改內(nèi)容
let template = fs.readFileSync(path.join(__dirname, templatePath), 'utf8');
//let content = template.replace(/TemplateDemo/g, componentName); // target file content
let content = template.replace(new RegExp(replaceStr,'g'), componentName); // target file content
// 目標(biāo)文件夾和目標(biāo)文件的路徑
let hostPath = __dirname
if(root.indexOf(":") > 0)
{
hostPath = ""
}
let targetDirPath = path.join(hostPath, root, componentName);
let targetFilePath = path.join(hostPath, root, componentName, templatePath.split("/")[3].replace("TemplateDemo",componentName));
// mkdirSync
if (!fs.existsSync(targetDirPath)) {
fs.mkdirSync(targetDirPath);
console.log('The ' + targetDirPath + ' folder has been created!');
}
// writeFile async
if (!fs.existsSync(targetFilePath)) {
fs.writeFile(targetFilePath, content, (err) => {
if (err) throw err;
console.log('The ' + targetFilePath + ' has been created!');
});
} else {
console.error('error!\n' + targetFilePath + ' has already been existed!');
}
}

4:代碼發(fā)布
可通過npm get registry 查看當(dāng)前設(shè)置的包來源,返回的哪個地址就是往那個倉庫上發(fā)布
1:執(zhí)行命令:npm login 輸入賬號、密碼、郵箱即可登錄
2:執(zhí)行命令:npm publish即可發(fā)布
代碼
https://github.com/leach-chen/TemplateCreateFile
個人網(wǎng)站(github資源庫)
https://www.leachchen.com