npm开发脚手架

1.安装相关包:

npm install  commander inquirer path co co-prompt fs-extra child_process 

依赖包一定要安装在dependencies里面,而不是devDependencies里面,否则在用npm install 时,会导致devDependencies的依赖包没有下载的问题。

2. 创建一个文件夹hyhweb-cli,在文件夹里面创建package.json文件,执行 git init 命令。

package.json内容如下:
{
  "name": "hyhweb-cli",
  "version": "1.0.1",
  "description": "vue-project-init",
  "bin": {
    "hyhweb": "bin/hyhweb.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "npm",
    "脚手架"
  ],
  "author": "hyhweb",
  "license": "ISC",
  "devDependencies": {
    "child_process": "^1.0.2",
    "co": "^4.6.0",
    "co-prompt": "^1.0.0",
    "commander": "^7.0.0",
    "fs-extra": "^9.1.0",
    "path": "^0.12.7"
  },
  "dependencies": {
    "execa": "^5.0.0",
    "inquirer": "^7.3.3"
  }
}

3.脚手架目录如下:

在这里插入图片描述

4.bin/hyhweb.js文件,主要注册commander命令的入口执行函数(action的回调函数),内容如下:

#!/usr/bin/env node

'use strict';

process.env.NODE_PATH = __dirname+'/../node_modules/';
const program = require('commander');

program
    .version(require('../package').version)
    .usage('<command> [options]')

program.command('create <projectName>')
    .option('--remote','clone remote git project')
    .description('create a new project, the options [--remote] is clone git')
    .action((programName,cmd)=>require('../command/init')(programName,cmd.remote));
program.parse(process.argv);
if(!program.args.length){
    program.help()
}

5.command/init.js 脚手架执行的任务都在这里实现(安装包,下载第三方资源等),内容如下:

const path = require('path');
const co = require('co');
const prompt = require('co-prompt');
const fs = require('fs-extra');
const exec = require('child_process').exec;
const inquirer = require('inquirer');
const getConfig= require('../template');


module.exports = (projectName,remote)=>{
    co(function* () {
        const templateName = yield prompt('template name(test):')
        const projectPath = path.resolve(process.cwd(),projectName);
        fs.emptyDir(projectPath,function (error) {
            handleError(error);
            console.log('\n finish clear dir');
            const fn = function () {
                console.log(`\n cd ${projectName} && npm install`);
                addPlugins(projectName).then(r => {
                    console.log('\n npm install  completed');
                });
            }
            clone(projectPath,templateName,fn)

        })
    })
    function handleError(error) {
        if(!error){ return false}
        console.log(error)
        process.exit();
    }
    function clone(projectPath,templateName,callback) {
        co(function* () {
                const config = getConfig[templateName];
                const url = config.url;
                const branch = config.branch;

                const cmdStr = `git clone -b ${branch} ${url} ${projectPath}`;
            console.log('\n git clone start ...');
                exec(cmdStr,(error)=>{
                    handleError(error);
                    console.log('\n git clone completed');
                    callback();
                })
        })

    }
    async function addPlugins(projectName) {

        const options =  await  inquirer.prompt([{
            name: 'plugins',
            type: 'checkbox',
            message: `install vue vue-router vuex? `,
            choices: ['vue','vue-router','vuex']
        }])
        const pluginsString = options.plugins.join(' ');
        if(options.plugins.length !=0){
            console.log(`\n ${pluginsString} install start ...`);
            const cmdStr =`cd ${projectName} && npm install ${pluginsString}`
            exec(cmdStr,(error)=>{
                handleError(error);
                console.log(`\n ${pluginsString} install completed`);
                process.exit();
            })
        }

    }

}

6.在package.json文件中添加bin对象:
如下:

  "bin": {
    "hyhweb": "bin/hyhweb.js"
  },
  1. 执行登录npm和发布:
    npm login
    npm publish

8.发布成功后可以访问脚手架:
https://www.npmjs.com/package/hyhweb-cli

9.在发布期间,遇到个问题,如下:

npm publish发布包时出现403错误no_perms Private mode enable, only admin can publish this module:
或者使用yarn publish出现couldn’t publish package:"https://registry.npm.taobao.org/包名:unauthorized"错误

出现原因:使用的是淘宝源cnpm,登陆到的是cnpm

解决方法:切换到npmjs的网址,代码如下

npm config set registry http://registry.npmjs.org/

如果对您有帮助,请点个赞,谢谢。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值