一、生成npm 开发包
二、本地调试
plugins: [
'npm-plugin/src/index.ts'
]
'npm-plugin':{
mode:'plugin',
}
三、插件开发
3.1、 api.describe
使用api.describe 进行插件注册
api.describez({
key:'npm-plugin',
config: {
schema(joi){
return joi.object({
mode: joi.string(),
})
}
}
})
key : 当前插件注册名称
config.default : 配置的默认值,用户没有配置时取这个
config.schema : 声明配置的类型,基于joi,如果你希望用户进行配置,这个是必须的,否则用户的配置无效
config.onChange: dev 阶段配置被修改后的处理机制,默认会重启dev进程,也可以修改为 api.ConfigChangeType.regenerateTmpFiles 只重新生成临时文件,还可以通过函数的格式自定义
enableBy : 启用方式,默认值注册启用,可更改为api.EnableBy.config, 还可以用自定义函数的方式决定其启用时机(动态生效)
3.2 api.addUmiExports
添加需要umi额外导出的内容,返回值格式为
{ source: string, specifers?: (string | (local: string, exported: string)) [], exportAll?: boollean }
比如api.addUmiExports(() => { source: 'dva', specifiers:['connect'] }),然后就可以通过
import {connect} from 'umi'
使用dva的connect来使用
api.addUmiExports(() => {
if(api.config['npm-plugin']?.mode){
return [ { specifiers: ['navgation'],
source:'../npm-plugin/export'
}
]
}
return []
})
3.3 addRuntimePlugin
添加运行时插件,返回值格式为表示文件路径的字符串
3.5 onGenerateFiles
生成临时文件,触发时机在webpack 编译之前
api.onGenerateFiles(() => {
api.writeTmpFile({
path:'any.ts',
content:""
})
})
3.6 writeTmpFile
writeTmpFile({path:string, content: string, skipTSChecck?: boolean})
四、运行增加js插件示例
import { IApi, utils } from 'umi'
import {join} from 'path'
import {readFileSync} from 'fs'
const {Mustache, winPath} = utils
export default (api: IApi) => {
api.describe({
key:'npm-plugin',
config: {
schema(joi){
return joi.object({
mode: joi.string()
})
}
}
})
}
const PATH_NAME ='npm-plugin'
//导出内容
api.addUmiExport(() => {
if(api.config['npm-plugin']?.mode){
return [
{
specifiers:['npm-plugin'],
source:'../npm-plugin/exports'
}
]
}
return []
})
const umiImpDir = api.paths.absTmpPath
api.addRuntimePlugin(() => {
return winPath(join(umiTmpDir!, NAVIGATION_DIR, 'exports.ts.tpl'),'utf-8')
api.writeTmpFile({
path:`${PATH_NAME}/exports.ts`,
content:Mustache.render(exportsTpl,{})
})
api.writeTmpFile({
path:'${PATH_NAME}/render.ts',
content: `
export async function render(oldRender){
if($!!api.config['npm-plugin']?.mode){
await new Promise((resolve) => {
var script = document.createElement('script')
script.src = 'https://dev/umi.js'
document.head.appendChild(script)
script.onload = resolve
})
}
oldRender()
}
`
})
})