Skip to content

Instantly share code, notes, and snippets.

@cletusw
Last active August 16, 2017 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cletusw/dc249069f5fd312fd110a588f5cac7bf to your computer and use it in GitHub Desktop.
Save cletusw/dc249069f5fd312fd110a588f5cac7bf to your computer and use it in GitHub Desktop.
Codemod: AMD in CommonJS style -> CommonJS
/**
* Run this with jscodeshift
* Live demo: https://astexplorer.net/#/gist/3aec6fa8858f3ec0e0a82ab5ec4ad32d/latest
*
* Converts:
* define(function (require) {
* var React = require('react');
* const props = { foo: 'bar' };
* return React.createClass(props);
* });
*
* to:
* module.exports = function () {
* var React = require('react');
* const props = { foo: 'bar' };
* return React.createClass(props);
* }();
*/
"use strict";
module.exports = function(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ExpressionStatement)
.filter(
path =>
path.parentPath.node.type === "Program" &&
path.node.expression.type === "CallExpression" &&
path.node.expression.callee.type === "Identifier" &&
path.node.expression.callee.name === "define" &&
path.node.expression.arguments.length === 1 &&
["FunctionExpression", "ArrowFunctionExpression"].indexOf(
path.node.expression.arguments[0].type
) >= 0 &&
path.node.expression.arguments[0].params.length === 1 &&
path.node.expression.arguments[0].params[0].type === "Identifier" &&
path.node.expression.arguments[0].params[0].name === "require"
)
.replaceWith(path => {
var fn = path.node.expression.arguments[0];
fn.params = [];
var returnValue = j.expressionStatement(j.assignmentExpression(
"=",
j.memberExpression(
j.identifier("module"),
j.identifier("exports")
),
j.callExpression(fn, [])
));
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