公共模塊
1
基礎模塊參照了vant的思路璃氢,使用bem命名規(guī)范。先創(chuàng)建一個命名空間艺配,這個命名空間返回創(chuàng)建組件函數(shù)與生成命名方法油航。在創(chuàng)建組件函數(shù)中創(chuàng)建name
與install
屬性用于注冊vue
組件
創(chuàng)建組件函數(shù)
創(chuàng)建base組件
npm run plop
# 輸入組件名稱得到packages/base模塊
在src文件夾中創(chuàng)建create
文件夾并創(chuàng)建component.ts
文件用于創(chuàng)建組件方法野建。創(chuàng)建組件與要name
屬性和install
方法來注冊組件
/**
* Create a basic component with common options
*/
import { App, defineComponent, ComponentOptionsWithObjectProps } from 'vue'
/**
*
* @description 創(chuàng)建組件
* @export createComponent
* @param {string} name
* @return {*} defineComponent
*/
export function createComponent (name: string) {
return function (sfc: ComponentOptionsWithObjectProps) {
sfc.name = name
sfc.install = (app: App) => {
app.component(name as string, sfc)
app.component(name), sfc)
}
return defineComponent(sfc)
} as typeof defineComponent
}
因為我們組件名字可能包含多個單詞所以我們把他轉換為駝峰命名法所以創(chuàng)建src/format/string.ts
文件來導出駝峰命名函數(shù)
// base/src/format/string.ts
const camelizeRE = /-(\w)/g
/**
*
* @description 把-換成駝峰命名
* @export camelize
* @param {string} str
* @return {*} {string}
*/
export function camelize (str: string): string {
return str.replace(camelizeRE, (_, c) => c.toUpperCase())
}
// base/src/create/component.ts
import { camelize } from '../format/string'
// 修改這句代碼來轉換為駝峰命名法
app.component(camelize(`-${name}`), sfc)
創(chuàng)建create/bem.ts
文件生成bem
的函數(shù)
Bem 函數(shù)傳入?yún)?shù)與生成的名字
- b() // 'button'
- b('text') // 'button__text'
- b({ disabled }) // 'button button--disabled'
- b('text', { disabled }) // 'button__text button__text--disabled'
- b(['disabled', 'primary']) // 'button button--disabled button--primary'
export type Mod = string | { [key: string]: any };
export type Mods = Mod | Mod[];
function gen (name: string, mods?: Mods): string {
if (!mods) {
return ''
}
if (typeof mods === 'string') {
return ` ${name}--${mods}`
}
if (Array.isArray(mods)) {
return mods.reduce<string>((ret, item) => ret + gen(name, item), '')
}
return Object.keys(mods).reduce(
(ret, key) => ret + (mods[key] ? gen(name, key) : ''),
''
)
}
/**
*
* @description 創(chuàng)建BEM命名空
* @export
* @param {string} name
* @return {*} string
*/
export function createBEM (name: string) {
return function (el?: Mods, mods?: Mods): Mods {
if (el && typeof el !== 'string') {
mods = el
el = ''
}
el = el ? `${name}__${el}` : name
return `${el}${gen(el, mods)}`
}
}
export type BEM = ReturnType<typeof createBEM>;
創(chuàng)建create/index.ts
文件罗岖,這個文件導出一個函數(shù)這個函數(shù)有一個參數(shù),這個參數(shù)就是創(chuàng)建組件的名字诅蝶,返回一個數(shù)組退个,這個數(shù)組的第一項是創(chuàng)建組件的方法精肃,第二項就是根據(jù)組件名字創(chuàng)建bem
命名規(guī)則的函數(shù)
import { createBEM } from './bem'
import { createComponent } from './component'
/**
*
* @description 創(chuàng)建命名空間
* @export
* @param {string} name
* @return {*} [createComponent(name), createBEM(name)]
*/
export function createNamespace (name: string) {
name = 'two-' + name
return [createComponent(name), createBEM(name)] as const
}
后續(xù)的公共的東西也會提取到公共base模塊中