Last active
August 16, 2017 21:28
-
-
Save cletusw/dc249069f5fd312fd110a588f5cac7bf to your computer and use it in GitHub Desktop.
Codemod: AMD in CommonJS style -> CommonJS
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
/** | |
* 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