我們在做新的頁面或組件時,會做很多重復(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.hbs 和 style.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)個贊,分享給小伙伴們吧~