本文主要重點在於實戰代碼,原理性的東西相信你們都能在其餘地方搜到就不講了javascript
工程目錄java
能夠直接負責,也能夠 npm init 。可是其中 bin 語句必不可少下面會講解到node
{
"name": "webpack4_cli_yhy",
"version": "1.0.2",
"description": "test-cli",
"main": "./index.js",
"keywords": [
"cli"
],
"bin": {
"webpack4-cli": "./index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"chalk": "^2.4.1",
"commander": "^2.19.0",
"download-git-repo": "^1.1.0",
"handlebars": "^4.0.12",
"inquirer": "^6.2.0",
"log-symbols": "^2.2.0",
"ora": "^3.0.0"
}
}
複製代碼
#!/usr/bin/env node
const fs = require('fs');
const program = require('commander');
const download = require('download-git-repo');
const handlebars = require('handlebars');
const inquirer = require('inquirer');
const ora = require('ora');
const chalk = require('chalk');
const symbols = require('log-symbols');
program.version('1.0.0', '-v, --version')
.command('init <name>')
.action((name) => {
if(!fs.existsSync(name)){
inquirer.prompt([
{
name: 'description',
message: '請輸入項目描述'
},
{
name: 'author',
message: '請輸入做者名稱'
}
]).then((answers) => {
const spinner = ora('正在下載模板...');
spinner.start();
download('yuhaiyang1/webpack4', name, (err) => {
if(err){
spinner.fail();
console.log(symbols.error, chalk.red(err));
}else{
spinner.succeed();
const fileName = `${name}/package.json`;
const meta = {
name,
description: answers.description,
author: answers.author
}
if(fs.existsSync(fileName)){
const content = fs.readFileSync(fileName).toString();
const result = handlebars.compile(content)(meta);
fs.writeFileSync(fileName, result);
}
console.log(symbols.success, chalk.green('項目初始化完成'));
}
})
})
}else{
// 錯誤提示項目已存在,避免覆蓋原有項目
console.log(symbols.error, chalk.red('項目已存在'));
}
})
program.parse(process.argv);
複製代碼
具體爲啥這麼寫能夠看下其餘大神文章我講下注意事項webpack
npm login && npm publish 而後發佈成功git
寫的比較倉促多多包涵github