LsAng Blog
2025

发布一个 npm 包

创建并发布 @llds/template 项目模板包的记录。

npm

@llds/template

效果

演示视频:04_1.mp4

用处

快速创建自己构建的项目模板。

实现

预期效果

终端输入 npx @llds/template,显示模板列表,选择模板,输入项目名称,即可创建项目。

依赖

  • @inquirer/prompts:命令行交互
  • simple-git:Git 操作
  • boxen:美化终端输出

核心代码(index.js)

#!/usr/bin/env node
import path from 'node:path'
import { input, select } from '@inquirer/prompts'
import boxen from 'boxen'
import ora from 'ora'
import simpleGit from 'simple-git'

const git = simpleGit()

const templateChoices = [
  { name: 'uonvue-template', value: 'git@github.com:llds66/uonvue-template.git' },
  { name: 'hono-cf-template', value: 'git@github.com:llds66/hono-cf-template.git' },
]

async function run() {
  const repoUrl = await select({ message: ' 请选择项目模板:', choices: templateChoices })
  const projectName = await input({ message: ' 请输入项目名称:', default: 'my-app' })
  if (!projectName) {
    console.error('项目名称不能为空')
    return
  }

  const targetDir = path.resolve(process.cwd(), projectName)
  const spinner = ora('正在拉取...').start()
  try {
    await git.clone(repoUrl, targetDir, ['--depth', '1'])
    spinner.succeed(' 模板克隆成功!')
    console.log(`\n✅ 项目已创建 ${projectName}`)
    console.log(`\n✅ 项目位置 ${targetDir}`)
    console.log(
      boxen(`\n  cd ${projectName} \n  pnpm i`, {
        title: '下一步',
        titleAlignment: 'center',
        width: 25,
        borderStyle: 'round',
        borderColor: 'green',
      }),
    )
  } catch (error) {
    spinner.fail('克隆模板失败')
    console.error('❌ 错误:', error.message || error)
  }
}

run()

发布

发布到 npm:npm publish

On this page