在Next.js使用Babel插件在编译阶段自动应用高阶组件

252 阅读1分钟

背景: 使用新版 nextjs 框架创建的 app-router 项目,因为接入next-intl 多语言包致使打包的page组件需要使用自定义高阶组件进行包装(我也不知道为什么,组内的人这样说的,没去探究原因,谁有空去看看源码),现使用自定义 babel plugin 对 page.js 文件进行 AST 自动实现HOC, 降低开发者心智负担

  1. 如何使用
npm i babel-plugin-injectcomponentcode -D

// babel.config.js
module.exports = {
    ...
    plugins: [
        ...
        [
            ['babel-plugin-injectcomponentcode', { 
                importComponentFilePath: '@/components/PageWrapper', 
                importComponentName: 'PageWrapper',
                isImportDefault: true, 
            }]
        ]
     ]
}
  1. 本质上就是识别到文件路径,在编译阶段对文件进行HOC行为,降低业务开发者 使用nextjs心智负担

  2. babel-plugin-injectcomponentcode有四个参数

    1. importComponentFilePath: 需要导入的组件的地址
    2. importComponentName: import 组件的 name
    3. isImportDefault(可选参数): 是否默认导出,默认是 true (默认导出就是 export default xxx 的意思)
    4. needWrapperFileRelativePath(可选参数): 需要被包裹的组件的相对路径
  3. 如果需要被包装的组件已经被准备HOC的组件包装过,那么此 babel 插件将不再进行高阶

  4. 仓库源码,欢迎star

效果:

### 输入

import xx from 'xx'
const Demo = () => {}
export default Demo

### 输出

import PageWrapper from '@/components/PageWrapper'
import xx from 'xx'
const Demo = () => {}
export default PageWrapper(Demo)