目錄
- 入口文件搭建
- 實現(xiàn)具體業(yè)務流程
入口文件搭建
- 首先
npm init
創(chuàng)建一個package.json
- 在
package.json
里面添加一個配置項中添加bin
{
"name": "node-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
// 項目入口文件
"bin": "cli.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
- 在根目錄下創(chuàng)建一個
cli.js
文件洛心,里面寫下面的內(nèi)容词身,頂格寫注釋(必寫)
#!/usr/bin/env node
console.log('cli working!')
#!/usr/bin/env node
Node CLI
應用入口文件必須要有這樣的文件頭
如果是Linux
或者macOS
系統(tǒng)下還需要修改此文件的讀寫權(quán)限為755
具體就是通過chmod 755 cli.js
實現(xiàn)修改
- 在當前目錄中運行
npm link
番枚,會自動創(chuàng)建一個package-lock.json
文件
{
"name": "node-cli",
"version": "1.0.0",
"lockfileVersion": 1
}
- 當前目錄運行
node-cli
node-cli
> cli working!
這樣入口文件就搭建完畢了~
實現(xiàn)具體業(yè)務流程
重溫一下腳手架的工作過程:
- 通過命令行交互詢問用戶問題(
node
中發(fā)起交互命令我們使用inquirer
模塊)- 根據(jù)用戶回答的結(jié)果生成文件(入口文件中進行邏輯實現(xiàn))
- 完成模板創(chuàng)建
在根目錄下創(chuàng)建templates
文件夾,創(chuàng)建兩個文件
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= name %></title>
</head>
<body>
</body>
</html>
- style.css
body{
margin: 0;
background-color: bisque;
}
- 安裝兩個npm模塊
# 用于命令行交互
npm install inquirer
# 用于模板引擎渲染
npm install ejs
- 編寫
cli.js
文件
- 引入需要的模塊
inquirer
的prompt
方法創(chuàng)建詢問深啤,數(shù)組里面的一個對象就是對應一個的問題then
里面根據(jù)拿到的answers
執(zhí)行任務
#!/usr/bin/env node
// 用于命令行交互
const inquirer = require('inquirer')
// 用戶獲取文件路徑
const path = require('path')
// 用于讀取寫入文件
const fs = require('fs')
// 用于模板引擎渲染
const ejs = require('ejs')
inquirer.prompt([
{
type:'input',
name:'name',
message: 'Project name?'
}
])
.then(answers => {
console.log(answers)
// 引入path模塊路星,模板目錄寫絕對路徑
const tmplDir = path.join(__dirname, 'templates')
// 目標目錄:目標執(zhí)行的目錄,一般在cwd目錄
const destDir = process.cwd()
// 引入fs模塊,將模板下面文件全部轉(zhuǎn)換到目標目錄
fs.readdir(tmplDir, (err, files) => {
if(err) throw err
files.forEach(file => {
// 文件的相對路徑
console.log(file) // index.html style.css
// 引入ejs模塊
// 通過模板引擎渲染路徑對應的文件
// 第一個參數(shù)是文件的絕對路徑
// 第二個參數(shù)是模板引擎工作時候的數(shù)據(jù)上下文
// 第三個參數(shù)是回調(diào)函數(shù)
ejs.renderFile(path.join(tmplDir, file), answers, (err, result) => {
if(err) throw err
// 成功的話就是已經(jīng)渲染過的文件
console.log(result)
// 寫入文件访诱,目標目錄絕對路徑韩肝,第二個參數(shù)是文件內(nèi)容
fs.writeFileSync(path.join(destDir, file), result)
})
})
})
})
- 創(chuàng)建另一個文件夾九榔,使用命令行
node-cli
> ? Project name? myProject
可以看到在新的項目中,生成了兩個文件
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>myProject</title>
</head>
<body>
</body>
</html>
- style.css
body{
margin: 0;
background-color: bisque;
}
這樣我們就完成了一個簡單的自制腳手架剩蟀。