Skip to content

Instantly share code, notes, and snippets.

@justinabrahms
Last active December 19, 2015 22:29
Show Gist options
  • Save justinabrahms/6027925 to your computer and use it in GitHub Desktop.
Save justinabrahms/6027925 to your computer and use it in GitHub Desktop.
Node.js script which transforms old-style AMD modules into modules with the sugar syntax outlined in http://requirejs.org/docs/whyamd.html#sugar The code is ugly and procedural, but it solves a need. *NOTE*: This hasn't yet been validated to work. Specifically it doesn't provide a return statement which the requirejs documentation indicates it s…
#!/usr/bin/env node
/**
* Transforms code from old-style requirejs modules into AMD sugared modules.
*
* define(['dep1','dep2'], function(arg1, arg2) {...})
*
* becomes:
*
* define(function(require) { var arg1 = require('dep1'), arg2 = require('dep2'); ... });
*
* Usage:
*
* ./require_sugar path/to/file
*
* will dump the new file out to stdout.
*/
var esprima = require('esprima')
, escodegen = require('escodegen')
, beautify = require('js-beautify').js_beautify
, fs = require('fs')
;
var filename = process.argv[2]
var results = fs.readFileSync(filename)
var output_options = {
format: {
indent: {
style: ' '
},
quotes: 'auto',
}
, comment: true
, parse: true
}
var ast = esprima.parse(results, { raw: true, tokens: true, range: true, comment: true });
ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
// loop over:
var fn_args = ast.body[0].expression.arguments
// for each, add to variable declaration
var var_dec = {
type: "VariableDeclaration"
, kind: "var"
, declarations: []
};
for (var i = 0; i < fn_args[0].elements.length; i++) {
// pulls out of fn_args[0] (the import path) and matches it up with param
// name from the same position in fn_args[1] and generates an AST node for the syntax:
//
// param = require('path')
var_dec.declarations.push({
type: "VariableDeclarator"
, id: {
type: "Identifier"
, name: fn_args[1].params[i].name
}
, init: {
type: "CallExpression"
, callee: {
type: "Identifier"
, name: "require"
}
, arguments: [
{
type: "Literal"
, value: fn_args[0].elements[i].value
, raw: fn_args[0].elements[i].raw
}
]
}
});
}
// prepend variable declaration to the function body
ast.body[0].expression.arguments[1].body.body.unshift(var_dec);
ast.body[0].expression.arguments.shift() // get rid of original array first param
ast.body[0].expression.arguments[0].params = [{type:"Identifier", name:"require"}] // require is the only param now.
var generated_code = escodegen.generate(ast, output_options);
var pretty = beautify(generated_code, {indent_size: 4});
console.log(pretty);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment