第 012 期 易學(xué)易用的模板代碼生成神器 - Plop

我們在做新的頁面或組件時,會做很多重復(fù)的初始化的工作。如創(chuàng)建類似的文件: 組件文件,樣式文件等。文件中寫類似的初始化代碼: 引入樣式,定義組件,導(dǎo)出組件等。

Plop 能幫你搞定這些重復(fù)工作。

Plop 介紹

Plop 是一個易學(xué),易用,且功能強(qiáng)大的腳手架工具。它能通過終端命令,接收參數(shù),創(chuàng)建你所需要的模板文件。

下面,我們以生成 React 的組件為例,介紹 Plop 的用法。

第 1 步 在項(xiàng)目中安裝 Plop

npm install --save-dev plop

第 2 步 配置 Plop
我們來實(shí)現(xiàn),輸入組件名稱,生成組件代碼的功能。組件名稱做為參數(shù),通過命令行中獲取。Plop 從命令行中獲取參數(shù),用的是 inquirer。

plopfile.js 是 Plop 的配置文件。在項(xiàng)目根目錄下新建 plopfile.js,內(nèi)容如下:

function main (plop) {
  plop.setGenerator('component', {
      description: '創(chuàng)建組件',
      // 命令行交互
      prompts: [
        {
          type: 'input',
          name: 'name',
          message: '組件名稱'
        }
      ],
      actions: data => {
        const componentName = toComponentName(data.name)
        const actions = [
          {
            // 添加組件文件
            type: 'add',
            // 生成的文件的地址
            path: `src/components/{{name}}/index.tsx`,
            // 模板文件地址
            templateFile: `plop-templates/component.hbs`,
            data: {// 傳入模板的參數(shù)
              componentName
            },
            skipIfExists: true
          },
          {
            // 添加樣式文件
            type: 'add',
            path: `src/components/{{name}}/style.scss`,
            templateFile: 'plop-templates/style.hbs',
            skipIfExists: true
          }
        ]
        return actions
      }
  });
}

function toComponentName(name) {
  let nameArray = name.split('-')
  return nameArray.map(item => `${item.charAt(0).toUpperCase()}${item.substr(1)}`).join('')
}

module.exports = main

第 3 步 創(chuàng)建模板文件
根據(jù)上一步配置中的模板文件路徑,創(chuàng)建目錄 plop-templates,并在該目錄下創(chuàng)建文件: component.hbsstyle.hbs

component.hbs 是組件模板,內(nèi)容如下:

import s from './style.scss'

interface I{{componentName}}Props {
  className?: string;
}

function {{componentName}}({ className }: I{{componentName}}Props) {
  return (
    <div></div>
  )
}

export default {{componentName}}

{{componentName}} 是從上一步中傳入的參數(shù)。Plop 解析模板用的是 handlebars。

style.hbs 是樣式模板。內(nèi)容為空,也可以些樣式的初始化代碼。

第 4 步 增加生成命令
package.json 中新增:

"script":{
    ...,
    "new":"plop"
}

第 5 步 運(yùn)行

npm run new

至此,一個簡單的固定模板就自動生成就寫好了。

當(dāng)然,Plop 的功能不止一次。Plop 支持根據(jù)參數(shù)來決定生成哪些文件。告別復(fù)制粘貼,用 Plop 來生成模板代碼吧~

覺得本文對你有幫助。點(diǎn)個贊,分享給小伙伴們吧~

參考文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容