Created
November 7, 2020 05:29
-
-
Save sunnylost/d1707d3c8e42771123e1ebeb5f1e42ba to your computer and use it in GitHub Desktop.
Transform lodash to lodash-es
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const path = require('path') | |
const parser = require('@babel/parser') | |
const traverse = require('@babel/traverse').default | |
const generator = require('@babel/generator').default | |
const t = require('@babel/types') | |
const prettier = require('prettier') | |
let code = fs.readFileSync(path.resolve(__dirname, './test/1.js'), { | |
encoding: 'utf8' | |
}) | |
const ast = parser.parse(code, { | |
sourceType: 'module' | |
}) | |
let lodashVar | |
let usedMethods = [] | |
traverse(ast, { | |
enter(path) { | |
let node = path.node | |
if (t.isImportDeclaration(node)) { | |
if (node.source.value === 'lodash' && node.specifiers) { | |
lodashVar = node.specifiers[0].local.name | |
} | |
} | |
if (t.isMemberExpression(node) && node.object.name === lodashVar) { | |
let methodName = node.property.name | |
!usedMethods.includes(methodName) && usedMethods.push(methodName) | |
path.parentPath.replaceWith( | |
t.callExpression(t.identifier(methodName), path.parent.arguments) | |
) | |
} | |
} | |
}) | |
traverse(ast, { | |
enter(path) { | |
let node = path.node | |
if (t.isImportDeclaration(node)) { | |
if (node.source.value === 'lodash' && node.specifiers) { | |
node.source.value = 'lodash-es' | |
node.specifiers = usedMethods.map((name) => t.identifier(name)) | |
} | |
} | |
} | |
}) | |
let generateCodes = generator(ast, {}, source).code | |
fs.writeFileSync( | |
path.resolve(__dirname, './test/2.js'), | |
prettier.format(generateCodes, { | |
parser: 'babel' | |
}), | |
{ | |
encoding: 'utf8' | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment