Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.