babel-plugin-lodash-demand-import

1.0.2 • Public • Published

babel按需引入lodash插件

使用说明

step 1: 安装 babel-plugin-lodash-demand-import

npm i babel-plugin-lodash-demand-import --save-dev   

step 2: 配置 babel-plugin-lodash-demand-import

{
    "plugins": ["babel-plugin-lodash-demand-import"]
}

或者:

./node_modules/.bin/babel src --out-dir lib --plugins babel-plugin-lodash-demand-import    

即可

源码如下:

module.exports = ({ types: t }) => {
    return {
        visitor: {
            ImportDeclaration(path, state) {
                if (path.get('source').isStringLiteral() && path.get('source').node.value === 'lodash') {
                    const variableSpecifiers = path.get('specifiers');
                    if (variableSpecifiers.length > 0) {
                        variableSpecifiers.map(item => {
                            if (item.node.type !== 'ImportDefaultSpecifier') {
                                const importDefaultSpecifier = [
                                    t.ImportDefaultSpecifier(t.Identifier(item.node.local.name)),
                                ];
                                const importDeclaration = t.ImportDeclaration(
                                    importDefaultSpecifier,
                                    t.StringLiteral(`lodash/${item.node.local.name}`)
                                );
                                path.parentPath.get('body')[0].insertBefore(importDeclaration)
                            }
                        })
                        path.remove();
                    }
                }
            }
        }
    }
}

Package Sidebar

Install

npm i babel-plugin-lodash-demand-import

Weekly Downloads

2

Version

1.0.2

License

ISC

Unpacked Size

3.1 kB

Total Files

3

Last publish

Collaborators

  • zzxiexin