Last active
April 26, 2018 07:24
-
-
Save patocallaghan/8fa7b8a1223ef80c15d7950b0afb017f to your computer and use it in GitHub Desktop.
Codemode to re-import Ember into our JS files
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
| /* 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