UNPKG

minipro-cli

Version:

微信小程序脚手架工具 ### Install

17 lines (14 loc) 10.5 kB
#!/usr/bin/env node !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */function e(e,o,n,t){return new(n||(n=Promise))((function(r,i){function s(e){try{a(t.next(e))}catch(e){i(e)}}function c(e){try{a(t.throw(e))}catch(e){i(e)}}function a(e){var o;e.done?r(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(s,c)}a((t=t.apply(e,o||[])).next())}))}const o=require("path");var n={templatePath:{project:o.join(__dirname,"../template/project"),page:o.join(__dirname,"../template/page"),component:o.join(__dirname,"../template/component")}};const t=require("fs");var r;!function(e){e["页面"]="page",e["组件"]="component"}(r||(r={}));var i={handlePath(e){const o=t.readdirSync(e),n={dir:[],file:[]};return o.forEach((o=>{var r=e+"/"+o;if(t.statSync(r).isDirectory()){n.dir.push(r);const e=this.handlePath(r);n.dir.push(...e.dir),n.file.push(...e.file)}else n.file.push(r)})),n},copy(e,o,n){return new Promise(((r,i)=>{try{const i=this.handlePath(e);t.access(o,(function(s){s&&t.mkdirSync(o),i.dir.forEach((n=>{t.mkdirSync(o+n.replace(e,""))})),i.file.forEach((r=>{var i,s;let c=o+"/"+r.replace(e,"");const a=(null===(i=null==n?void 0:n.writeBefore)||void 0===i?void 0:i.call(n,r))||"";t.writeFileSync(a||c,t.readFileSync(r)),null===(s=null==n?void 0:n.writeAfter)||void 0===s||s.call(n,c)})),r(!0)}))}catch(e){i(e)}}))},findPagePath:e=>JSON.parse(t.readFileSync(e)).pages[0].split("/").slice(0,-2).join("/"),formatCopy(e,o,n){return new Promise(((r,i)=>{t.mkdirSync(o);const{name:s}=n;this.copy(e,o,{writeBefore(e){const n=e.split(".")[1];return`${o}/${s}.${n}`}}).then((()=>{r(!0)})).catch((e=>{i(e)}))}))}};const s=require("chalk");var c={success(e){console.log(s.green(`>> ${e}`))},error(e){console.log(s.red(`>> ${e}`))},warn(e){console.log(s.yellow(`>> ${e}`))}};const a=require("fs"),l=require("handlebars"),p=require("path");const m={},u=require("path"),d=require("fs");function h(){if(Object.keys(m).length)return m;{const e=process.cwd(),o=u.resolve(e,"./project.config.json");if(d.existsSync(o)){m.rootPath=e,m.projectJsonPath=o,m.miniJson=u.resolve(e,"./minicli.json");const n=i.handlePath(e).file;if(n.length)for(let e=0,o=n.length;e<o;e++)if(n[e].endsWith("app.json")){m.appJsonPath=n[e];break}return m.appJsonPath?(m.pagePrefix=i.findPagePath(m.appJsonPath),m.pagePath=u.resolve(m.appJsonPath,`../${m.pagePrefix}`)):c.error("app.json 不存在,请确认后重试"),m.appJsonPath&&(m.componentPath=u.resolve(m.appJsonPath,"../components"),m.componentPrefix=m.componentPath.replace(u.resolve(m.appJsonPath,"../"),"")),m}return c.error("project.config.json 不存在,请切换到项目根目录进行命令行操作"),null}}function f(e,o){const n=h();if(n){const t=n.appJsonPath,i=n.pagePrefix;if(o===r.页面)return u.resolve(t,`../${i}/${e}`);if(o===r.组件)return u.resolve(t,`../components/${e}`)}}const g=require("fs"),v=n.templatePath.page;const y=require("fs"),P=require("path");function $(e,o){const n=h();if(!n)return;const{appJsonPath:t,pagePrefix:r,componentPrefix:i}=n;let s=P.resolve(t,`../${r}/${e}/${e}.json`);if(!y.existsSync(s)){const o=P.resolve(t,`../${i}/${e}/${e}.json`);if(!y.existsSync(o))return void c.error("不存在对应的页面和组件,请重新确认路径。");s=o}const a=JSON.parse(y.readFileSync(s)),l=P.resolve(t,`../components/${o}/${o}`);y.existsSync(`${l}.json`)?(a.usingComponents?a.usingComponents[o]=l.replace(P.resolve(t,"../"),""):a.usingComponents={[o]:l.replace(P.resolve(t,"../"),"")},y.writeFileSync(s,JSON.stringify(a,null,2)),c.success(`为${e} 引入组件 ${o} 成功`)):c.error(`不存在对应的组件文件,请重新确认路径。path: ${l}`)}const j=require("fs"),S=n.templatePath.component,w=require("inquirer");const q=require("inquirer"),x=[{type:"list",name:"mode",message:"选择想要创建的模版",choices:["project","page","component"]},{type:"input",name:"name",default:e=>"project"===e.mode?"mini-pro":"index",message:e=>`设置 ${e.mode} 名称 (e.g: ${"project"===e.mode?"mini-pro":"index"}):`},{type:"input",name:"appId",message:"设置小程序项目的appid",default:"",when:e=>"project"===e.mode},{type:"input",name:"libVersion",message:"设置小程序项目的微信基础库版本",default:"2.7.3",when:e=>"project"===e.mode}];function J(){q.prompt(x).then((o=>{const{name:t,mode:s}=o;switch(s){case"project":!function(o){e(this,void 0,void 0,(function*(){const{name:e}=o,t=n.templatePath.project,r=p.join(process.cwd(),"./"+e);a.existsSync(r)?c.error("当前project路径已存在,请重新确认,path:"+r):i.copy(t,r,{writeAfter(e){e.endsWith("project.config.json")&&a.readFile(e,"utf-8",((n,t)=>{const r=l.compile(t)(o);a.writeFile(e,r,(e=>{e&&c.error("更新自定义配置文件失败")}))}))}}).then((()=>{c.success("生产 project 模板成功!")})).catch((e=>{c.error(`生成模板失败 ${e}`)}))}))}(o);break;case"page":!function(o){e(this,void 0,void 0,(function*(){const e=h();if(!e)return;const n=f(o,r.页面);if(g.existsSync(n))c.error(`存在 Page: ${n} ,请重新确认路径`);else if(yield i.formatCopy(v,n,{name:o}).catch(console.log)){let n=JSON.parse(g.readFileSync(e.appJsonPath));n.pages.push(`${e.pagePrefix}/${o}/${o}`),g.writeFileSync(e.appJsonPath,JSON.stringify(n,null,2)),c.success("生成 Page 模板成功")}else c.error("生成 Page 模板失败")}))}(t);break;case"component":!function(o){e(this,void 0,void 0,(function*(){if(!h())return;const e=f(o,r.组件),n=j.existsSync(e);n?c.error(`存在 Component: ${n} ,请重新确认路径`):((yield i.formatCopy(S,e,{name:o}).catch(console.log))?c.success("生成 Component 模板成功"):c.error("生成 Component 模板失败"),w.prompt([{type:"input",name:"pageStr",message:"是否需要在某些页面或组件中引入,输入多个以,隔开(e.g: index,about)",default:"否"}]).then((e=>{const{pageStr:n}=e;"否"!==n&&n.split(",").forEach((e=>{$(e,o)}))})))}))}(t)}}))}const k=require("fs"),b=require("inquirer"),C=require("child_process"),F=require("path");function N(e){const o=["版本升级: ","特性更新: ","修订补丁: "];let n=e;/(\d+.){2,3}\d+/g.test(n)||(n="1.0.0",c.warn("配置的 version 不符合规范, 已默认修正为1.0.0"));for(let e=0;e<o.length;e++){const t=n.split(".").map(((o,n)=>n===e?Number(o)+1:o)).join(".");o[e]=o[e]+t}return o.unshift("no change"),o}function O(){return e(this,void 0,void 0,(function*(){const e=h();if(!e)return;const{rootPath:o,projectJsonPath:n,miniJson:t}=e;if(!k.existsSync(t))return c.error("需要配置 minicli.json 以提供小程序命令行工具安装地址及小程序版本信息"),void c.warn("具体微信小程序命令行工具说明,请查看:https://developers.weixin.qq.com/miniprogram/dev/devtools/cli.html");const r=JSON.parse(k.readFileSync(t)),{version:i,cliPath:s}=r;if(!i)return void c.error("需要在 minicli.json中提供 version 字段");if(!s)return c.error("需要在 minicli.json中提供 cliPath 字段"),void c.warn("安装地址请查看:https://developers.weixin.qq.com/miniprogram/dev/devtools/cli.html");const a=yield b.prompt(function(e){return[{type:"list",name:"version",message:`设置上传的版本号 (当前版本号: ${e}):`,default:1,choices:N(e),filter:o=>"no change"===o?e:o.split(": ")[1]},{type:"input",name:"versionDesc",message:"写一个简单的介绍来描述这个版本的改动过:",default:"a little change"}]}(i)).catch(console.log);n||c.error("未找到 project.config.json,请重新确认路径");const l=F.resolve(n,"../");console.log("开始上传体验版 ..."),C.execSync(`${s} upload --project ${l} -v ${a.version} -d "${a.versionDesc}"`,{stdio:"inherit"}),r.version=a.version,r.versionDesc=a.versionDesc,k.writeFileSync(t,JSON.stringify(r,null,2)),C.execSync(`cd ${o}`)}))}const _=require("../package").version,D=require("commander"),E=require("chalk"),A=require("leven");D.version(_,"-v, --version"),D.usage("<command> [options]"),D.command("create").description("创建项目/页面/组件").action((()=>J())),D.command("invoke <pageName> <componentName>").alias("ic").description("为某个页面引入项目内某个组件").action(((e,o)=>$(e,o))),D.command("publish").description("发布版本").action((()=>O().catch(console.log))),D.arguments("<command>").action((e=>{D.outputHelp(),console.log(" "+E.red(`Unknown command ${E.yellow(e)}.`)),console.log(),function(e){let o;D.commands.map((e=>e._name)).forEach((n=>{const t=A(n,e)<A(o||"",e);A(n,e)<3&&t&&(o=n)})),o&&(console.log(" "+E.red(`Did you mean ${E.yellow(o)}?`)),console.log())}(e),process.exitCode=1})),D.on("--help",(()=>{console.log(),console.log(` Run ${E.cyan("minipro-cli <command> -h, --help")} for detailed usage of given command.`),console.log(),console.log(`${E.cyan("Tips:")} ${E.yellow("除 minipro-cli create [project] 选项外,其余命令需要在小程序根目录下执行")}`),console.log()})),D.commands.forEach((e=>e.on("--help",(()=>{if("invoke"===e._name)console.log(),console.log(`${E.cyan("e.g:")} minipro-cli ic index nav-list`);else if("publish"===e._name){console.log(),console.log(`${E.cyan("Tips:")} ${E.yellow("需要在小程序根级目录配置 minicli.json 以提供当前小程序版本信息。")}`),console.log(),console.log(`${E.cyan("Example (minicli.json):")}`),console.log();const e={version:"1.0.0",versionDesc:"版本描述",cliPath:"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"};console.log(JSON.stringify(e,null,2)),console.log(),console.log(`${E.cyan("微信小程序命令行安装地址cliPath,请查看:https://developers.weixin.qq.com/miniprogram/dev/devtools/cli.html")}`)}console.log()})))),D.parse(process.argv)}));