Skip to content

Instantly share code, notes, and snippets.

@cletusw
Created August 16, 2017 21:30
Show Gist options
  • Select an option

  • Save cletusw/14324a4c3bf320abaab9fee68c912ab9 to your computer and use it in GitHub Desktop.

Select an option

Save cletusw/14324a4c3bf320abaab9fee68c912ab9 to your computer and use it in GitHub Desktop.

Revisions

  1. cletusw created this gist Aug 16, 2017.
    66 changes: 66 additions & 0 deletions amd-to-common.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    /**
    * 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();
    };