「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

2025-05-29 0 72

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

前言

为什么要写这篇文章呢?是因为最近一直在搞Strve.js生态,在自己捣鼓框架的同时也学到了很多东西。所以就本篇文章给大家介绍一种更加方便灵活的命令行脚手架工具,以及如何发布到NPM上。

之前,我也写过类似的开发命令行工具的文章,但是核心思想都是通过代码远程拉取Git仓库中的项目模板代码。有时候会因为网速的原因导致拉取失败,进而会初始化项目失败。

那么,有没有比这个更好的方案呢?那么本篇就来了。

最近,使用Vite工具开发了很多项目。不得不佩服尤老师惊人的代码能力,创建了这么好的开发工具,开发体验非常丝滑。尤其是你刚初始化项目时,只需要执行一行命令,也不用全局安装什么工具。然后,自定义选择需要的模板进行初始化项目,就大功告成了!这种操作着实把我惊到了!我在想,如果我把create-vite的这种思路应用到我自己的脚手架工具中是不是很Nice!

实战

所以,二话不说,就抓紧打开ViteGitHub地址。

https://github.com/vitejs

找了大半天,终于找到了命令行工具核心代码。

https://github.com/vitejs/vite/tree/main/packages/create-vite

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

映入眼帘的是很多以template-开头的文件夹,打开几个都看了一下,都是框架项目模板。那么,可以先放在一边。

下一步,我们就打开index.js文件看下什么内容。我列下代码,大家可以简单看一下,不用深究。

  1. #!/usr/bin/env node
  2. // @ts-check
  3. const fs = require(\’fs\’)
  4. const path = require(\’path\’)
  5. // Avoids autoconversion to number of the project name by defining that the args
  6. // non associated with an option ( _ ) needs to be parsed as a string. See #4606
  7. const argv = require(\’minimist\’)(process.argv.slice(2), { string: [\’_\’] })
  8. // eslint-disable-next-line node/no-restricted-require
  9. const prompts = require(\’prompts\’)
  10. const {
  11. yellow,
  12. green,
  13. cyan,
  14. blue,
  15. magenta,
  16. lightRed,
  17. red
  18. } = require(\’kolorist\’)
  19. const cwd = process.cwd()
  20. const FRAMEWORKS = [
  21. {
  22. name: \’vanilla\’,
  23. color: yellow,
  24. variants: [
  25. {
  26. name: \’vanilla\’,
  27. display: \’JavaScript\’,
  28. color: yellow
  29. },
  30. {
  31. name: \’vanilla-ts\’,
  32. display: \’TypeScript\’,
  33. color: blue
  34. }
  35. ]
  36. },
  37. {
  38. name: \’vue\’,
  39. color: green,
  40. variants: [
  41. {
  42. name: \’vue\’,
  43. display: \’JavaScript\’,
  44. color: yellow
  45. },
  46. {
  47. name: \’vue-ts\’,
  48. display: \’TypeScript\’,
  49. color: blue
  50. }
  51. ]
  52. },
  53. {
  54. name: \’react\’,
  55. color: cyan,
  56. variants: [
  57. {
  58. name: \’react\’,
  59. display: \’JavaScript\’,
  60. color: yellow
  61. },
  62. {
  63. name: \’react-ts\’,
  64. display: \’TypeScript\’,
  65. color: blue
  66. }
  67. ]
  68. },
  69. {
  70. name: \’preact\’,
  71. color: magenta,
  72. variants: [
  73. {
  74. name: \’preact\’,
  75. display: \’JavaScript\’,
  76. color: yellow
  77. },
  78. {
  79. name: \’preact-ts\’,
  80. display: \’TypeScript\’,
  81. color: blue
  82. }
  83. ]
  84. },
  85. {
  86. name: \’lit\’,
  87. color: lightRed,
  88. variants: [
  89. {
  90. name: \’lit\’,
  91. display: \’JavaScript\’,
  92. color: yellow
  93. },
  94. {
  95. name: \’lit-ts\’,
  96. display: \’TypeScript\’,
  97. color: blue
  98. }
  99. ]
  100. },
  101. {
  102. name: \’svelte\’,
  103. color: red,
  104. variants: [
  105. {
  106. name: \’svelte\’,
  107. display: \’JavaScript\’,
  108. color: yellow
  109. },
  110. {
  111. name: \’svelte-ts\’,
  112. display: \’TypeScript\’,
  113. color: blue
  114. }
  115. ]
  116. }
  117. ]
  118. const TEMPLATES = FRAMEWORKS.map(
  119. (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name]
  120. ).reduce((a, b) => a.concat(b), [])
  121. const renameFiles = {
  122. _gitignore: \’.gitignore\’
  123. }
  124. async function init() {
  125. let targetDir = argv._[0]
  126. let template = argv.template || argv.t
  127. const defaultProjectName = !targetDir ? \’vite-project\’ : targetDir
  128. let result = {}
  129. try {
  130. result = await prompts(
  131. [
  132. {
  133. type: targetDir ? null : \’text\’,
  134. name: \’projectName\’,
  135. message: \’Project name:\’,
  136. initial: defaultProjectName,
  137. onState: (state) =>
  138. (targetDir = state.value.trim() || defaultProjectName)
  139. },
  140. {
  141. type: () =>
  142. !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : \’confirm\’,
  143. name: \’overwrite\’,
  144. message: () =>
  145. (targetDir === \’.\’
  146. ? \’Current directory\’
  147. : `Target directory \”${targetDir}\”`) +
  148. ` is not empty. Remove existing files and continue?`
  149. },
  150. {
  151. type: (_, { overwrite } = {}) => {
  152. if (overwrite === false) {
  153. throw new Error(red(\’✖\’) + \’ Operation cancelled\’)
  154. }
  155. return null
  156. },
  157. name: \’overwriteChecker\’
  158. },
  159. {
  160. type: () => (isValidPackageName(targetDir) ? null : \’text\’),
  161. name: \’packageName\’,
  162. message: \’Package name:\’,
  163. initial: () => toValidPackageName(targetDir),
  164. validate: (dir) =>
  165. isValidPackageName(dir) || \’Invalid package.json name\’
  166. },
  167. {
  168. type: template && TEMPLATES.includes(template) ? null : \’select\’,
  169. name: \’framework\’,
  170. message:
  171. typeof template === \’string\’ && !TEMPLATES.includes(template)
  172. ? `\”${template}\” isn\’t a valid template. Please choose from below: `
  173. : \’Select a framework:\’,
  174. initial: 0,
  175. choices: FRAMEWORKS.map((framework) => {
  176. const frameworkColor = framework.color
  177. return {
  178. title: frameworkColor(framework.name),
  179. value: framework
  180. }
  181. })
  182. },
  183. {
  184. type: (framework) =>
  185. framework && framework.variants ? \’select\’ : null,
  186. name: \’variant\’,
  187. message: \’Select a variant:\’,
  188. // @ts-ignore
  189. choices: (framework) =>
  190. framework.variants.map((variant) => {
  191. const variantColor = variant.color
  192. return {
  193. title: variantColor(variant.name),
  194. value: variant.name
  195. }
  196. })
  197. }
  198. ],
  199. {
  200. onCancel: () => {
  201. throw new Error(red(\’✖\’) + \’ Operation cancelled\’)
  202. }
  203. }
  204. )
  205. } catch (cancelled) {
  206. console.log(cancelled.message)
  207. return
  208. }
  209. // user choice associated with prompts
  210. const { framework, overwrite, packageName, variant } = result
  211. const root = path.join(cwd, targetDir)
  212. if (overwrite) {
  213. emptyDir(root)
  214. } else if (!fs.existsSync(root)) {
  215. fs.mkdirSync(root)
  216. }
  217. // determine template
  218. template = variant || framework || template
  219. console.log(`\\nScaffolding project in ${root}…`)
  220. const templateDir = path.join(__dirname, `template-${template}`)
  221. const write = (file, content) => {
  222. const targetPath = renameFiles[file]
  223. ? path.join(root, renameFiles[file])
  224. : path.join(root, file)
  225. if (content) {
  226. fs.writeFileSync(targetPath, content)
  227. } else {
  228. copy(path.join(templateDir, file), targetPath)
  229. }
  230. }
  231. const files = fs.readdirSync(templateDir)
  232. for (const file of files.filter((f) => f !== \’package.json\’)) {
  233. write(file)
  234. }
  235. const pkg = require(path.join(templateDir, `package.json`))
  236. pkg.name = packageName || targetDir
  237. write(\’package.json\’, JSON.stringify(pkg, null, 2))
  238. const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent)
  239. const pkgManager = pkgInfo ? pkgInfo.name : \’npm\’
  240. console.log(`\\nDone. Now run:\\n`)
  241. if (root !== cwd) {
  242. console.log(` cd ${path.relative(cwd, root)}`)
  243. }
  244. switch (pkgManager) {
  245. case \’yarn\’:
  246. console.log(\’ yarn\’)
  247. console.log(\’ yarn dev\’)
  248. break
  249. default:
  250. console.log(` ${pkgManager} install`)
  251. console.log(` ${pkgManager} run dev`)
  252. break
  253. }
  254. console.log()
  255. }
  256. function copy(src, dest) {
  257. const stat = fs.statSync(src)
  258. if (stat.isDirectory()) {
  259. copyDir(src, dest)
  260. } else {
  261. fs.copyFileSync(src, dest)
  262. }
  263. }
  264. function isValidPackageName(projectName) {
  265. return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(
  266. projectName
  267. )
  268. }
  269. function toValidPackageName(projectName) {
  270. return projectName
  271. .trim()
  272. .toLowerCase()
  273. .replace(/\\s+/g, \’-\’)
  274. .replace(/^[._]/, \’\’)
  275. .replace(/[^a-z0-9-~]+/g, \’-\’)
  276. }
  277. function copyDir(srcDir, destDir) {
  278. fs.mkdirSync(destDir, { recursive: true })
  279. for (const file of fs.readdirSync(srcDir)) {
  280. const srcFile = path.resolve(srcDir, file)
  281. const destFile = path.resolve(destDir, file)
  282. copy(srcFile, destFile)
  283. }
  284. }
  285. function isEmpty(path) {
  286. return fs.readdirSync(path).length === 0
  287. }
  288. function emptyDir(dir) {
  289. if (!fs.existsSync(dir)) {
  290. return
  291. }
  292. for (const file of fs.readdirSync(dir)) {
  293. const abs = path.resolve(dir, file)
  294. // baseline is Node 12 so can\’t use rmSync 🙁
  295. if (fs.lstatSync(abs).isDirectory()) {
  296. emptyDir(abs)
  297. fs.rmdirSync(abs)
  298. } else {
  299. fs.unlinkSync(abs)
  300. }
  301. }
  302. }
  303. /**
  304. * @param {string | undefined} userAgent process.env.npm_config_user_agent
  305. * @returns object | undefined
  306. */
  307. function pkgFromUserAgent(userAgent) {
  308. if (!userAgent) return undefined
  309. const pkgSpec = userAgent.split(\’ \’)[0]
  310. const pkgSpecArr = pkgSpec.split(\’/\’)
  311. return {
  312. name: pkgSpecArr[0],
  313. version: pkgSpecArr[1]
  314. }
  315. }
  316. init().catch((e) => {
  317. console.error(e)
  318. })

看到上面这么多代码是不是不想继续阅读下去了?不要慌!我们其实就用到里面几个地方,可以放心的继续阅读下去。

这些代码算是Create Vite核心代码了,我们会看到常量FRAMEWORKS定义了一个数组对象,另外数组对象中都是一些我们初始化项目时需要选择安装的框架。所以,我们可以先ViteGithub项目Clone下来,试试效果。

然后,将项目Clone下来之后,我们找到/packages/create-vite这个文件夹,我们现在就只关注这个文件夹。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

我用的Yarn依赖管理工具,所以我首先使用命令初始化依赖。

  1. yarn

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

然后,我们可以先打开根目录下的package.json文件,会发现有如下命令。

  1. {
  2. \”bin\”: {
  3. \”create-vite\”: \”index.js\”,
  4. \”cva\”: \”index.js\”
  5. }
  6. }

我们可以在这里起一个自己模板的名字,比如我们就叫demo,

  1. {
  2. \”bin\”: {
  3. \”create-demo\”: \”index.js\”,
  4. \”cvd\”: \”index.js\”
  5. }
  6. }

然后,我们先在这里使用yarn link命令来将此命令在本地可以运行。

然后再运行create-demo命令·。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

会显示一些交互文本,会发现非常熟悉,这正是我们创建Vite项目时所看到的。我们在前面说到我们想实现一个属于自己的项目模板,现在我们也找到了核心。所以就开始干起来吧!

我们会看到在根目录下有很多template-开头的文件夹,我们打开一个看一下。比如template-vue。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

原来模板都在这!但是这些模板文件都是以template-开头,是不是有什么约定?所以,我们打算回头再去看下index.js文件。

  1. // determine template
  2. template = variant || framework || template
  3. console.log(`\\nScaffolding project in ${root}…`)
  4. const templateDir = path.join(__dirname, `template-${template}`)

果真,所以模板都必须以template-开头。

那么,我们就在根目录下面建一个template-demo文件夹,里面再放一个index.js文件,作为示例模板。

我们在执行初始化项目时发现,需要选择对应的模板,那么这些选项是从哪里来的呢?我们决定再回去看下根目录下的index.js文件。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

会发现有这么一个数组,里面正是我们要选择的框架模板。

  1. const FRAMEWORKS = [
  2. {
  3. name: \’vanilla\’,
  4. color: yellow,
  5. variants: [
  6. {
  7. name: \’vanilla\’,
  8. display: \’JavaScript\’,
  9. color: yellow
  10. },
  11. {
  12. name: \’vanilla-ts\’,
  13. display: \’TypeScript\’,
  14. color: blue
  15. }
  16. ]
  17. },
  18. {
  19. name: \’vue\’,
  20. color: green,
  21. variants: [
  22. {
  23. name: \’vue\’,
  24. display: \’JavaScript\’,
  25. color: yellow
  26. },
  27. {
  28. name: \’vue-ts\’,
  29. display: \’TypeScript\’,
  30. color: blue
  31. }
  32. ]
  33. },
  34. {
  35. name: \’react\’,
  36. color: cyan,
  37. variants: [
  38. {
  39. name: \’react\’,
  40. display: \’JavaScript\’,
  41. color: yellow
  42. },
  43. {
  44. name: \’react-ts\’,
  45. display: \’TypeScript\’,
  46. color: blue
  47. }
  48. ]
  49. },
  50. {
  51. name: \’preact\’,
  52. color: magenta,
  53. variants: [
  54. {
  55. name: \’preact\’,
  56. display: \’JavaScript\’,
  57. color: yellow
  58. },
  59. {
  60. name: \’preact-ts\’,
  61. display: \’TypeScript\’,
  62. color: blue
  63. }
  64. ]
  65. },
  66. {
  67. name: \’lit\’,
  68. color: lightRed,
  69. variants: [
  70. {
  71. name: \’lit\’,
  72. display: \’JavaScript\’,
  73. color: yellow
  74. },
  75. {
  76. name: \’lit-ts\’,
  77. display: \’TypeScript\’,
  78. color: blue
  79. }
  80. ]
  81. },
  82. {
  83. name: \’svelte\’,
  84. color: red,
  85. variants: [
  86. {
  87. name: \’svelte\’,
  88. display: \’JavaScript\’,
  89. color: yellow
  90. },
  91. {
  92. name: \’svelte-ts\’,
  93. display: \’TypeScript\’,
  94. color: blue
  95. }
  96. ]
  97. }
  98. ]

所以,可以在后面数组后面再添加一个对象。

  1. {
  2. name: \’demo\’,
  3. color: red,
  4. variants: [
  5. {
  6. name: \’demo\’,
  7. display: \’JavaScript\’,
  8. color: yellow
  9. }
  10. ]
  11. }

好,你会发现我这里会有个color属性,并且有类似颜色值的属性值,这是依赖kolorist导出的常量。kolorist是一个将颜色放入标准输入/标准输出的小库。我们在之前那些模板交互文本会看到它们显示不同颜色,这正是它的功劳。

  1. const {
  2. yellow,
  3. green,
  4. cyan,
  5. blue,
  6. magenta,
  7. lightRed,
  8. red
  9. } = require(\’kolorist\’)

我们,也将模板对象添加到数组里了,那么下一步我们执行命令看下效果。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

会发现多了一个demo模板,这正是我们想要的。

我们继续执行下去。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

我们会看到根目录下已经成功创建了demo1文件夹,并且里面正是我们想要的demo模板。

上图显示的Error,是因为我没有在demo模板上创建package.json文件,所以这里可以忽略。你可以在自己的模板里创建一个package.json文件。

虽然,我们成功在本地创建了自己的一个模板,但是,我们只能本地创建。也就是说你换台电脑,就没有办法执行这个创建模板的命令。

所以,我们要想办法去发布到云端,这里我们发布到NPM上。

首先,我们重新新建一个项目目录,将其他模板删除,只保留我们自己的模板。另外,将数组中的其他模板对象删除,保留一个自己的模板。

我以自己的模板create-strve-app为例。

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

然后,我们打开package.json文件,需要修改一些信息。

以create-strve-app为例:

  1. {
  2. \”name\”: \”create-strve-app\”,
  3. \”version\”: \”1.3.3\”,
  4. \”license\”: \”MIT\”,
  5. \”author\”: \”maomincoding\”,
  6. \”bin\”: {
  7. \”create-strve-app\”: \”index.js\”,
  8. \”cs-app\”: \”index.js\”
  9. },
  10. \”files\”: [
  11. \”index.js\”,
  12. \”template-*\”
  13. ],
  14. \”main\”: \”index.js\”,
  15. \”private\”: false,
  16. \”keywords\”: [\”strve\”,\”strvejs\”,\”dom\”,\”mvvm\”,\”virtual dom\”,\”html\”,\”template\”,\”string\”,\”create-strve\”,\”create-strve-app\”],
  17. \”engines\”: {
  18. \”node\”: \”>=12.0.0\”
  19. },
  20. \”repository\”: {
  21. \”type\”: \”git\”,
  22. \”url\”: \”git+https://github.com/maomincoding/create-strve-app.git\”
  23. },
  24. \”bugs\”: {
  25. \”url\”: \”https://github.com/maomincoding/create-strve-app/issues\”
  26. },
  27. \”homepage\”: \”https://github.com/maomincoding/create-strve-app#readme\”,
  28. \”dependencies\”: {
  29. \”kolorist\”: \”^1.5.0\”,
  30. \”minimist\”: \”^1.2.5\”,
  31. \”prompts\”: \”^2.4.2\”
  32. }
  33. }

注意,每次发布前,version字段必须与之前不同,否则发布失败。

最后,我们依次运行如下命令。

切换到npm源

  1. npm config set registry=https://registry.npmjs.org

登录NPM(如果已登录,可忽略此步)

  1. npm login

发布NPM

  1. npm publish

我们可以登录到NPM(https://www.npmjs.com/)

查看已经发布成功!

「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架

以后,我们就可以直接运行命令下载自定义模板。这在我们重复使用模板时非常有用,不仅可以提升效率,而且还可以避免犯很多不必要的错误。

结语

另外,此篇举例的 Create Strve App 是一套快速搭建Strve.js项目的命令行工具。如果你对此感兴趣,可以访问以下地址查看源码:

https://github.com/maomincoding/create-strve-app

熬夜奋战二个多月,Strve.js生态初步已经建成,以下是Strve.js 最新文档地址,欢迎浏览。

https://maomincoding.github.io/strvejs-doc/

原文链接:https://mp.weixin.qq.com/s/2ndyBAQZRro4-9NonHPP2Q

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 「Create-?」每个前端开发者都可以拥有属于自己的命令行脚手架 https://www.kuaiidc.com/91172.html

相关文章

发表评论
暂无评论