webpack动态导入本地组件
使用条件:
本地组件统一收拢在一个index.*文件中,从该文件中export出所有组件

  • index.ts文件:

    1
    2
    3
    4
    5
    6
    import a from './a.ts'
    import b from './a.ts'
    export {
    a,
    b
    }
  • 引入

    1
    2
    // 假设上面的`index.ts`文件存在`@/components`目录下
    import {a} from '@/components'

使用插件babel-plugin-import
同antd一样

babel-plugin-import

安装

1
npm i babel-plugin-import -D

配置

配置文件babel.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module.exports = {
//...
plugins: [
/** 本地组件库的按需引入 */
[
'import',
{
//库的名字,需同引入组件使用的名字一样 `@/components`
libraryName: '@/components',
//是否将驼峰转为下划线形式
camel2UnderlineComponentName: false,
//是否将驼峰转为破折号形式
camel2DashComponentName: true,
customName: function(name) {
//此处返回自定义组件的具体路径
return `@/components/${name}/index.ts`
}
}
]
]
//...
}

使用组件的方法

1
import { NotFound } from '@/components' // 此处的 `@/components` 需与上面配置的 `libraryName` 相同

本文地址: http://gehaiqing.com/2019/06/13/webpack-dynamic-import-local-component/