We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
脚手架工作原理: 向用户询问预设问题 结合用户回答和一些模板文件生成项目结构
脚手架工作原理:
步骤:
创建一个package.json
yarn init
安装项目所需要的依赖
yarn add inquirer yarn add ejs
指定cli入口文件:通过package.json中的bin字段指定
//./package.json { "bin": "cli.js" }
cli.js
#!/usr/bin/env node // Node CLI 应用入口文件必须要有这样的文件头 // 如果是 Linux 或者 macOS 系统下还需要修改此文件的读写权限为 755 // 具体就是通过 chmod 755 cli.js 实现修改 const fs = require('fs') const path = require('path') const inquirer = require('inquirer') const ejs = require('ejs') inquirer.prompt([//inquirer.prompt:发起一个命令行的询问,数组中每个命令行成员就是发起的一个问题 { type: 'input',//问题输入方式 name: 'name',//问题返回值的键值 message: 'Project name?'//给用户的提示 } ]) .then(anwsers => { console.log(anwsers)//问题接收到的用户的答案 // 根据用户回答的结果生成文件 // 模板目录 const tmplDir = path.join(__dirname, 'templates') // 目标目录 const destDir = process.cwd()// destDir是node的方法 fs.readdir(tmplDir, (err, files) => { // readdir自动扫描tmplDir下的文件 if (err) throw err files.forEach(file => {// file得到的是相对路径,通过模板引擎渲染文件 ejs.renderFile(path.join(tmplDir, file), anwsers, (err, result) => { if (err) throw err // 将结果写入目标文件路径 console.log(result) fs.writeFileSync(path.join(destDir, file), result) }) }) }) })
模板文件:
templates/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 %></name></title> <!-- 通过<%=%>获得询问环境得到的用户询问答案 --> </head> <body> </body> </html>
templates/style.css
body{ height: auto; }
命令行创建一个空文件夹test进行测试
mkdir test cd test define-scaffold
The text was updated successfully, but these errors were encountered:
No branches or pull requests
步骤:
创建一个package.json
安装项目所需要的依赖
指定cli入口文件:通过package.json中的bin字段指定
cli.js
模板文件:
templates/index.html
templates/style.css
命令行创建一个空文件夹test进行测试
The text was updated successfully, but these errors were encountered: