babel-plugin-onex-utils
v0.2.3
Published
> TODO: description
Downloads
12
Readme
babel-plugin-onex-utils
onex-utils
工具库的babel
插件,挑选出你使用onex-utils
的模块,剔除未使用的模块,减小项目引用
Install
$ npm i --save onex-utils
$ npm i --save-dev babel-plugin-onex-utils @babel/cli @babel/preset-env
Example
Transforms
import { capitalize, map } from 'onex-utils';
map([], capitalize);
roughly to
"use strict";
var _map2 = _interopRequireDefault(require("onex-utils/build/utils/map"));
var _capitalize2 = _interopRequireDefault(require("onex-utils/build/utils/capitalize"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
(0, _map2["default"])([], _capitalize2["default"]);
Usage
.babelrc
{
"plugins": ["onex-utils"],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}
Babel API
require('babel-core').transform('code', {
'plugins': ['onex-utils'],
'presets': [['@babel/env', { 'targets': { 'node': 6 } }]]
})
webpack.config.js
'module': {
'loaders': [{
'loader': 'babel-loader',
'test': /\.js$/,
'exclude': /node_modules/,
'query': {
'plugins': ['onex-utils'],
'presets': [['@babel/env', { 'targets': { 'node': 6 } }]]
}
}]
}
Reference
Implementation approach
- 首先通过分析
ast
语法树中Program
节点分析整个import
语句中引用 - 分析完成之后,调用
import
中每个local
节点的,获取到对应的节点和引用,然后遍历这些引用,通过@babel/helper-module-imports
创建新形式的import
,并替换原有的语法 - 然后回溯
ImportDeclaration
过程删除对应的默认引用 - 针对
export
形式的导出,首先将其转化成单个依赖的import
语句,然后在进行变量导出