babel-plugin-import
原文档链接:github.com/umijs/babel…
英文较烂,有条件推荐阅读官方文档喔~
-
作用: 加载
babel
,antd
,lodash
等模块, 自动导入对应样式和JS文件 -
场景:
使用
antd
时, 需要加载组件的样式antd/dist/antd.css
, 但是我们大部分时候不需要使用到antd
所有的组件, 更不需要载入所有组件的样式。所以
antd
提供了按需引入import Button from 'antd/lib/button'; import 'antd/lib/button/style';
而
babel-plugin-import
能够帮助我们在引入组件的时候自动加载相关样式。 -
使用:
- 安装
npm install babel-plugin-import --save-dev
// .babelrc { "plugins":[ [ "import", option ] ] } // 需要实现多个引入, 可以添加多个import配置数组 // .babelrc { "plugins": [ [ "import", { "libraryName": "antd", "libraryDirectory": "lib" }, "antd" ], [ "import", { "libraryName": "antd-mobile", "libraryDirectory": "lib" }, "antd-mobile" ] ] }
- 安装
-
配置选项:
option必须是一个对象
-
"libraryName"
: 加载库的名字 -
"libraryDirectory"
:引入库相对于其
package.json
所在的目录, 即package.json
中的main
选项, 默认为lib。 -
"style"
:-
"true"
: 模块化导入js和css / less / sass源文件在编译期间可进行优化, 大大减少打包体积, 具体取决于使用
-
"css"
模块化导入js和css, 库预先内置的css文件将原样导入 -
Function
: 当传入为函数, 导入filepath
等于函数返回值的文件, 当返回值为false
, 则不导入文件如果你需要自己编写插件, 这对你来说将非常有用
[ "import", { "libraryName": "antd", "style": (name: string, file: Object) => { if(name === 'antd/lib/utils'){ return false; } return `${name}/style/2x`; } } ]
-
-
"styleLibraryDirectory"
: 默认null
, 用于引用样式的文件路径,原本样式将被忽略。常用来设置主题
theme
{ "libraryName": "element-ui", "styleLibraryDirectory": "lib/theme-chalk", } import { Button } from 'element-ui'; ↓ ↓ ↓ ↓ ↓ ↓ var _button = require('element-ui/lib/button'); require('element-ui/lib/theme-chalk/button');
-
"camel2DashComponentName"
: 默认true
, 可以设置为 false 来禁止驼峰转下划线import { TimePicker } from "antd" ↓ ↓ ↓ ↓ ↓ ↓ var _button = require('antd/lib/TimePicker');
-
"customName"
: 接受一个函数当我们设置
"camel2DashComponentName"
为false
, 我们可以自定义配置引入文件的名字。[ "import", { "libraryName": "antd", "customName": (name: string, file: object) => { const filename = file.opts.filename; if (name === 'TimePicker'){ return 'antd/lib/custom-time-picker'; } if (filename.indexOf('/path/to/my/different.js') >= 0) { return 'antd/lib/custom-name'; } return `antd/lib/${name}`; } } ]
在有些情况下, 转换器会将配置文件序列化为对象 (类似
JSON.parse
), 序列化不接收函数值的属性, 会导致customName
丢失所以我们可以使用
javascript
源文件路径来避免发生丢失:首先调用
path
模块处理路径[ "import", { "libraryName": "antd", "customName": require('path').resolve(__dirname, './customName.js') } ]
其次当模块导出的时候
module.exports = function customName(name) { return `antd/lib/${name}`; };
-
"customStyleName"
: 用来处理样式文件的customName
-
"transformToDefaultImport"
: 如果打包后的模块没有默认导出, 则请设置为false
-
-
注意事项
如果将库添加到webpack第三方库的配置文件中,
babel-plugin-import
将无法正常工作 -
引用
简单实现 babel-plugin-import 插件 juejin.cn/post/690570…