背景: 使用新版 nextjs 框架创建的
app-router项目,因为接入next-intl多语言包致使打包的page组件需要使用自定义高阶组件进行包装(我也不知道为什么,组内的人这样说的,没去探究原因,谁有空去看看源码),现使用自定义 babel plugin 对page.js文件进行 AST 自动实现HOC, 降低开发者心智负担
- 如何使用
npm i babel-plugin-injectcomponentcode -D
// babel.config.js
module.exports = {
...
plugins: [
...
[
['babel-plugin-injectcomponentcode', {
importComponentFilePath: '@/components/PageWrapper',
importComponentName: 'PageWrapper',
isImportDefault: true,
}]
]
]
}
-
本质上就是识别到文件路径,在编译阶段对文件进行
HOC行为,降低业务开发者 使用nextjs心智负担 -
babel-plugin-injectcomponentcode有四个参数importComponentFilePath: 需要导入的组件的地址importComponentName: import 组件的 nameisImportDefault(可选参数): 是否默认导出,默认是 true (默认导出就是 export default xxx 的意思)needWrapperFileRelativePath(可选参数): 需要被包裹的组件的相对路径
-
如果需要被包装的组件已经被准备
HOC的组件包装过,那么此 babel 插件将不再进行高阶
效果:
### 输入
import xx from 'xx'
const Demo = () => {}
export default Demo
### 输出
import PageWrapper from '@/components/PageWrapper'
import xx from 'xx'
const Demo = () => {}
export default PageWrapper(Demo)