如何自定义一个前端脚手架

96 阅读2分钟

创建前端脚手架步骤

  1. 基本结构设计
my-cli/
  ├── bin/              # 可执行文件目录
  ├── lib/              # 源码目录
  ├── templates/        # 模板文件
  └── package.json      # 项目配置
  1. 主要依赖


{
  "name": "my-cli",
  "version": "1.0.0",
  "bin": {
    "my-cli": "./bin/cli.js"
  },
  "dependencies": {
    "commander": "^8.0.0",    // 命令行工具
    "inquirer": "^8.0.0",     // 交互式命令
    "download-git-repo": "^3.0.2", // 下载模板
    "chalk": "^4.0.0",        // 命令行样式
    "ora": "^5.0.0"          // 加载动画
  }
}
  1. CLI入口文件


#!/usr/bin/env node

const program = require('commander');
const create = require('../lib/create');

program
  .version('1.0.0')
  .command('create <project-name>')
  .description('create a new project')
  .action((name) => {
    create(name);
  });

program.parse(process.argv);
  1. 创建项目逻辑


const inquirer = require('inquirer');
const downloadGitRepo = require('download-git-repo');
const ora = require('ora');
const chalk = require('chalk');

async function create(projectName) {
  const answer = await inquirer.prompt([
    {
      type: 'list',
      name: 'template',
      message: '请选择项目模板',
      choices: ['vue', 'react', 'node']
    }
  ]);

  const spinner = ora('downloading template...');
  spinner.start();

  downloadGitRepo(
    `direct:https://github.com/your-templates/${answer.template}`,
    projectName,
    { clone: true },
    (err) => {
      if (err) {
        spinner.fail();
        console.log(chalk.red(`创建失败:${err}`));
        return;
      }
      spinner.succeed();
      console.log(chalk.green('创建成功'));
    }
  );
}

module.exports = create;
  1. 发布命令
npm link          # 本地测试
npm publish       # 发布到npm

#!/usr/bin/env node 作用解释

  1. 作用
  • 被称为 "Shebang" 或 "Hashbang"
  • 指定脚本解释器的路径
  • 告诉系统使用 NODE_PATH 环境变量中找到的 node 解释器来执行此文件
  1. 工作原理
#!/usr/bin/env node
# 等同于执行:
/usr/bin/env node your-script.js
  1. 为什么用 env
  • 不同系统 node 安装位置可能不同
  • /usr/bin/env 会在 PATH 中查找 node
  • 增加脚本的可移植性
  1. 使用场景


#!/usr/bin/env node

const program = require('commander');
// ...rest of CLI code
  1. 权限设置
# Windows 不需要
# Linux/Mac 需要设置可执行权限
chmod +x ./bin/cli.js

npm link 作用解释

  1. 主要功能
  • 创建全局软链接(symlink)
  • 用于本地开发和测试 npm 包
  • 避免重复发布到 npm 仓库进行测试
  1. 使用步骤
# 1. 在开发的包目录下
cd my-package
npm link  # 创建全局链接

# 2. 在使用该包的项目中
cd my-project
npm link my-package  # 链接到全局包
  1. 工作原理
my-package/                # 包目录
  └── node_modules/       # 本地依赖
       └── my-package     # 软链接到全局

全局 node_modules/        # 全局目录
  └── my-package         # 软链接到源码
  1. 取消链接
# 在使用该包的项目中
npm unlink my-package

# 在包目录中
npm unlink
  1. 使用场景
  • 本地包开发调试
  • 多项目共享代码
  • 避免频繁发布测试版本