分析實(shí)現(xiàn)步驟:
- 通過 yarn 初始化一個(gè)項(xiàng)目
- 在 package.json 添加一個(gè) cli 入口文件 bin 字段
- 通過inquirer 模塊實(shí)現(xiàn)命令行交互
- 詢問用戶問題番枚,拿到配置結(jié)果
- 根據(jù)用戶回答生成模版文件
package.json文件
{
"name": "sample-scaffolding",
"version": "1.0.0",
"main": "index.js",
"bin": "cli.js",
"license": "MIT",
"dependencies": {
"ejs": "^3.1.6",
"inquirer": "^8.1.2"
}
}
cli.js文件
#!/usr/bin/env node
// Node CLI應(yīng)用入口文件必須要有種這樣的文件頭
// 這是告訴系統(tǒng),下面這個(gè)腳本氯哮,使用nodejs來執(zhí)行
// 如果是Linux或者macOS系統(tǒng)辙纬,還需要修改此文件的讀寫權(quán)限755
// sudo chmod -R 755 myResources
const inquirer = require('inquirer');
const path = require('path');
const fs = require('fs');
const ejs = require('ejs');
inquirer
.prompt([
{
type: 'input',
name: 'name',
message: '項(xiàng)目名字是啥烈菌?',
},
])
.then((anwsers) => {
// 模版目錄
const tempDir = path.join(__dirname, 'templates');
// 目標(biāo)目錄
const destDir = process.cwd();
// 將模板下的文件全部轉(zhuǎn)換到目標(biāo)目錄
fs.readdir(tempDir, (err, files) => {
if (err) throw err;
files.forEach((file) => {
// 通過模版引擎渲染文件
ejs.renderFile(path.join(tempDir, file), anwsers, (err, result) => {
if (err) throw errfs;
fs.writeFileSync(path.join(destDir, file), result);
});
});
});
});
目錄結(jié)構(gòu)
image.png