Skip to content

Instantly share code, notes, and snippets.

@jeffpeterson
Last active December 15, 2016 18:46
Show Gist options
  • Save jeffpeterson/aaf606f0628009d6eaf4 to your computer and use it in GitHub Desktop.
Save jeffpeterson/aaf606f0628009d6eaf4 to your computer and use it in GitHub Desktop.
Converts commonJS requires to es6 imports
// converts commonJS requires to es6 imports
// var foo = require('foo');
// ->
// import foo from 'foo';
//
// jscodeshift -t requiresToImports.js src/**/*.js*
module.exports = function(fileInfo, api) {
var j = api.jscodeshift;
return j(fileInfo.source)
.find(j.VariableDeclaration, {
declarations: [{
type: 'VariableDeclarator',
init: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require',
}
}
}]
})
.filter(isTopLevel)
.forEach(function(path) {
const dec = path.value.declarations[0];
const id = dec.id;
const source = dec.init.arguments[0];
path.replace(j.importDeclaration([{type: "ImportDefaultSpecifier", id: id}], source));
})
.toSource() + '\n';
}
function isTopLevel(path) {
return !path.parentPath.parentPath.parentPath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment