1.0.2 • Published 1 year ago

babel-plugin-lodash-demand-import v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

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();
                    }
                }
            }
        }
    }
}
1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago