跳到主要内容

制作 NPM 模板脚手架

3 分钟阅读

概述

在平时进行新项目开发的时候,重新搭建项目目录费时又费力,而且这些内容还和旧项目的工作内容有很高的耦合度,为了提高开发效率,创建一个完整且高度可配置的脚手架会是一个明智的选择。

通过预定义的项目模板,其中包含了一系列已经配置好的文件、目录结构和依赖项,可以帮助我们快速启动新项目,省去手动搭建项目的繁琐步骤,同时保持项目结构的一致性以及代码规范。

开始

在这里参考了 vite 和 nuxt 的脚手架的实现原理。

package.json 配置参考

{
"name": "template-framework",
"version": "1.0.0",
"description": "This is a create application framework.",
"main": "index.js",
"bin": {
"create-template": "index.js",
},
"author": "",
"license": "MIT",
"dependencies": {
"fs-extra": "^11.1.1",
"minimist": "^1.2.8"
}
}

制作模板生成脚本

//index.js
#!/usr/bin/env node
const path = require('path')
const fs = require('fs-extra')
const argv = require('minimist')(process.argv.slice(2))

async function init() {
const targetDir = argv._[0] || '.'
const cwd = process.cwd()
const root = path.join(cwd, targetDir)
const renameFiles = {
_gitignore: '.gitignore',
}
console.log(`Scaffolding project in ${root}...`)

await fs.ensureDir(root)
const existing = await fs.readdir(root)
if (existing.length) {
console.error(`Error: target directory is not empty.`)
process.exit(1)
}

const templateDir = path.join(
__dirname,
`template-${argv.t || argv.template || 'default'}`
)
const write = async (file, content) => {
const targetPath = renameFiles[file]
? path.join(root, renameFiles[file])
: path.join(root, file)
if (content) {
await fs.writeFile(targetPath, content)
} else {
await fs.copy(path.join(templateDir, file), targetPath)
}
}

const files = await fs.readdir(templateDir)
for (const file of files.filter((f) => f !== 'package.json')) {
await write(file)
}

const pkg = require(path.join(templateDir, `package.json`))
pkg.name = path.basename(root)
await write('package.json', JSON.stringify(pkg, null, 2))

console.log(`\nDone. Now run:\n`)
if (root !== cwd) {
console.log(` cd ${path.relative(cwd, root)}`)
}
console.log(` npm install (or \`yarn\`)`)
console.log(` npm run dev (or \`yarn dev\`)`)
console.log()
}

init().catch((e) => {
console.error(e)
})

模板文件夹命名格式

  • template-default 默认模板
  • template-popular 这样的命名在后续安装时只需添加 --template popular 这样的命令选项即可指定模板风格。

测试

node index.js abc

如果成功创建 abc 文件夹则脚手架成功搭建。

如果你想要指定模板你可以这样

node index.js abc --template <NewTemplate>

<NewTemplate> 是指定的模板,这需要你创建相对于的文件夹。

测试没有问题后可以选择上传到 npm 中方便以后搭建

npm publish

上传到npm后可以选择使用 npx 进行部署也可以选择全局安装后调用 create-template 指令。

npx template-framework abc
#or
npm template-framework -g
create-template

推荐使用 npx 方法来进行模板的安装,因为这样可以保证安装的是最新的模板并且无需担心全局命令冲突的问题。

评论
0条评论

添加新评论

昵称
邮箱
网址