Skip to content

Instantly share code, notes, and snippets.

@patocallaghan
Last active April 26, 2018 07:24
Show Gist options
  • Select an option

  • Save patocallaghan/8fa7b8a1223ef80c15d7950b0afb017f to your computer and use it in GitHub Desktop.

Select an option

Save patocallaghan/8fa7b8a1223ef80c15d7950b0afb017f to your computer and use it in GitHub Desktop.
Codemode to re-import Ember into our JS files
/* eslint-env node */
export default function(file, api, options) {
let j = api.jscodeshift;
let printOptions = options.printOptions || { quote: 'single' };
let root = j(file.source);
let emberRegex = /^Em(ber)?$/;
let emberModule = {
source: {
value: 'ember',
},
};
function hasEmberModule() {
return !!root.find(j.ImportDeclaration, emberModule).length;
}
function getEmberUsage() {
let usage = '';
root.find(j.Identifier).forEach(i => {
if (
i
&& i.value
&& i.value.name
) {
if (emberRegex.test(i.value.name)) {
usage = i.value.name;
}
}
});
return usage;
}
function getEmberGlobal() {
let global = '';
root.find(j.ExportDefaultDeclaration).forEach(i => {
if (
i
&& i.node
&& i.node.declaration
&& i.node.declaration.callee
&& i.node.declaration.callee.object
&& i.node.declaration.callee.object.object
&& i.node.declaration.callee.object.object.name
) {
let name = i.node.declaration.callee.object.object.name;
if (emberRegex.test(name)) {
global = name;
}
}
});
return global;
}
let emberGlobal = getEmberUsage();
if (!hasEmberModule() && emberGlobal) {
j(root.find(j.Declaration).at(0).get())
.insertBefore(
j.importDeclaration([j.importDefaultSpecifier(j.identifier(emberGlobal))], j.literal('ember')),
)
}
return root.toSource(printOptions);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment