Skip to content
New issue

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

如何自定义一个小型脚手架工具 #7

Open
janeLLLL opened this issue Sep 7, 2020 · 0 comments
Open

如何自定义一个小型脚手架工具 #7

janeLLLL opened this issue Sep 7, 2020 · 0 comments

Comments

@janeLLLL
Copy link
Owner

janeLLLL commented Sep 7, 2020

脚手架工作原理:

  1. 向用户询问预设问题
  2. 结合用户回答和一些模板文件生成项目结构

步骤:

  1. 创建一个package.json

    yarn init
    
  2. 安装项目所需要的依赖

    • inquirer:用户询问模块
    • ejs:模板引擎
    yarn add inquirer
    yarn add ejs
    
  3. 指定cli入口文件:通过package.json中的bin字段指定

    //./package.json
    {
        "bin": "cli.js"
    }
  4. 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)
          })
        })
      })
    })
  5. 模板文件:

    • 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;
      }
  6. 命令行创建一个空文件夹test进行测试

    mkdir test
    cd test
    define-scaffold
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant