从0到1打造一款脚手架:项目搭建

29 阅读1分钟

初始化 package.json

新建项目目录 next-cli 与 package.json 文件。

npm init -y

需要添加 bin 信息,bin 是配置命令名与脚本路径。命令名是next-cli,脚本路径是bin/main.js。 包名为 next-cli

{
  "name": "next-cli",
  "version": "1.0.0",
  "description": "一个神奇的脚手架工具",
  "main": "index.js",
  "bin": {
    "next-cli": "bin/main.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Wanan",
  "license": "ISC"
}

脚本文件

脚本文件bin/main.js ,用 commander来向用户展示脚手架功能,用 chalk来处理高亮显示。该文件主要是处理交互与显示,脚手架的核心逻辑放到 lib/create.js

安装依赖:npm i commander @vue/cli-shared-utils

  • #!/usr/bin/env node表明该文件是可执行文件。
  • commander 描述脚手架基本功能。
  • create() 为脚手架核心逻辑。
#!/usr/bin/env node

const program = require('commander')
const { chalk } = require('@vue/cli-shared-utils')
const create = require('../lib/create')

program
  .version(`next-cli ${require('../package').version}`)
  .usage('<command> [options]')

program
  .command('create <app-name>')
  .description('创建项目')
  .action((name, options) => {
    console.log(chalk.bold.blue(`Next CLI V1.0.0`))
    create(name, options)
  })

program.on('--help', () => {
  console.log()
  console.log(`  Run ${chalk.yellow(`next-cli <command> --help`)} for detailed usage of given command.`)
  console.log()
})

program.parse(process.argv)

lib/create.js 简单实现打印路径和项目名

const path = require('path')

module.exports = async (projectName) => {
  // 命令运行时的目录
  const cwd = process.cwd()
  // 目录拼接项目名
  const targetDir = path.resolve(cwd, projectName || '.')
  console.log(`创建项目的目录路径: ${targetDir}`);
}

建立链接

接下来测试前面编码的功能。一般的,我们是发包到 npm 上,然后安装使用。为了方便开发测试,不采用这种方式,而是通过软链接到全局执行环境然后使用。 用 npm link 命令可以将该 npm 包与命令软链接到全局执行环境,从而在任意位置可直接使用该命令。 在 next-cli 目录执行npm link

image.png

然后,可以在任意位置使用命令next-cli

image.png

运行 create 命令

next-cli create demo

image.png

到此,脚手架踏出了一小步。

本节代码

gitee.com/meahu/next-…