Created
August 16, 2017 21:30
-
-
Save cletusw/14324a4c3bf320abaab9fee68c912ab9 to your computer and use it in GitHub Desktop.
A codemod to transform amd style includes into commonjs includes
This file contains 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
/** | |
* Modified from https://github.com/skratchdot/amd-to-commonjs-codemod | |
*/ | |
const buildRequire = (j, v, r) => { | |
let code = ""; | |
if (v && v.type === "Identifier" && v.name.length) { | |
code += `const ${v.name}`; | |
} | |
if (r && r.type === "Literal" && r.value.length) { | |
if (code.length) { | |
code += " = "; | |
} | |
code += `require('${r.value}')`; | |
} | |
code += ";"; | |
if (code === ";") { | |
code = ""; | |
} | |
return code; | |
}; | |
module.exports = function(file, api) { | |
const j = api.jscodeshift; | |
return j(file.source) | |
.find(j.CallExpression) | |
.filter( | |
path => | |
path.parentPath.parentPath.node.type === "Program" && | |
path.parentPath.node.type === "ExpressionStatement" && | |
path.node.type === "CallExpression" && | |
path.node.callee.type === "Identifier" && | |
path.node.callee.name === "define" && | |
path.node.arguments.length === 2 && | |
path.node.arguments[0].type === "ArrayExpression" && | |
["FunctionExpression", "ArrowFunctionExpression"].indexOf(path.node.arguments[1].type) >= 0 | |
) | |
.replaceWith(path => { | |
const arrayExpression = path.node.arguments[0]; | |
const functionExpression = path.node.arguments[1]; | |
const comments = path.node.comments; | |
const result = []; | |
const statementSize = Math.max(functionExpression.params.length, arrayExpression.elements.length); | |
for (let i = 0; i < statementSize; i++) { | |
result.push(buildRequire(j, functionExpression.params[i], arrayExpression.elements[i])); | |
} | |
let spliceIndex = functionExpression.body.body.findIndex( | |
bodyNode => bodyNode.type !== "ExpressionStatement" || bodyNode.expression.type !== "Literal" | |
); | |
functionExpression.body.body.splice(spliceIndex, 0, ...result); | |
functionExpression.params = []; | |
var returnValue; | |
if (functionExpression.body.body.some(bodyNode => bodyNode.type === "ReturnStatement")) { | |
returnValue = j.assignmentExpression( | |
"=", | |
j.memberExpression(j.identifier("module"), j.identifier("exports")), | |
j.callExpression(functionExpression, []) | |
); | |
} else { | |
returnValue = j.callExpression(functionExpression, []); | |
} | |
returnValue.comments = path.node.comments; | |
return returnValue; | |
}) | |
.toSource(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment