首页 > 代码库 > 自定义脚手架

自定义脚手架

前提:

  目录结构

    my-project

      └ bin

          └myapp.js

      └ package.json

//myapp.js的内容如下

技术分享
#!/usr/bin/env node
const fs = require(‘fs‘);
const dirPath = process.cwd();
const argvss = process.argv.slice(2);

function createPublicFun(dirName) {
    this.dirName = dirName || "myApp";//默认创建myApp项目;
    this.cmd = ‘cd ‘+this.dirName+‘ && npm i jquery‘;//初始化npm依赖;
    this.public = function() {
        var shell = require(‘shelljs‘);
        shell.exec(cmd);
        console.log("初始化完成!")
    }
    if(!fs.existsSync(dirPath+"\\"+ this.dirName)){
        fs.mkdir(dirPath+"\\"+ this.dirName);
        fs.mkdir(dirPath+"\\"+ this.dirName+"\\node_modules");
    };
    this.public();
}
switch (argvss[0]){
    case ‘new‘:
        if(argvss[1]){
            createPublicFun(argvss[1]);
        }else{
            console.log("项目名称不能为空!")
        }
        break;
    case "init":
        if(argvss[1]){
            createPublicFun(argvss[1]);
        }else{
            createPublicFun();
        }
        break;
    default:
        console.log("命令错误!");
        break;
}
process.exit();//退出
View Code

//package.json的内容如下

例如简单的package.json:

{
  "name": "my-project-name",
  "version": "0.1.0",
  "bin":"bin/myapp.js"  
}

注意:package.json里面的【bin】必须指向某个js,个人建议默认执行bin/**.js

最后只要安装在全局就可以了。具体教程在 https://www.npmjs.com/package/init-cli_zys

自定义脚手架