Skip to content

Commit

Permalink
Sort and replace provide and requires in one pass
Browse files Browse the repository at this point in the history
  • Loading branch information
tschaub committed Feb 4, 2017
1 parent 329ec70 commit ea04523
Showing 1 changed file with 9 additions and 16 deletions.
25 changes: 9 additions & 16 deletions transforms/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ module.exports = function(info, api) {
// store any initial comments
const {comments} = root.find(j.Program).get('body', 0).node;

const replacements = {};

// replace goog.provide()
let provide;
root.find(j.ExpressionStatement, getGoogExpressionStatement('provide'))
Expand All @@ -105,41 +107,32 @@ module.exports = function(info, api) {
if (!provide) {
throw new Error(`No provide found in ${info.path}`);
}

// replace all uses of provided name with renamed identifier
if (provide.indexOf('.') > 0) {
root.find(j.MemberExpression, getMemberExpression(provide))
.replaceWith(j.identifier(rename(provide)));
} else {
root.find(j.Identifier, {name: provide})
.replaceWith(j.identifier(rename(provide)));
}
replacements[provide] = rename(provide);

// replace goog.require()
const requires = {};
root.find(j.ExpressionStatement, getGoogExpressionStatement('require'))
.replaceWith(path => {
const name = path.value.expression.arguments[0].value;
if (name in requires) {
if (name in replacements) {
throw new Error(`Duplicate require found in ${info.path}: ${name}`);
}
const renamed = rename(name);
requires[name] = renamed;
replacements[name] = renamed;
return j.variableDeclaration('var', [
j.variableDeclarator(j.identifier(renamed), j.callExpression(
j.identifier('require'), [j.literal(resolve(provide, name))]
))
]);
});

// replace all uses of required names with renamed identifiers
Object.keys(requires).sort().reverse().forEach(name => {
// replace all uses of required or provided names with renamed identifiers
Object.keys(replacements).sort().reverse().forEach(name => {
if (name.indexOf('.') > 0) {
root.find(j.MemberExpression, getMemberExpression(name))
.replaceWith(j.identifier(requires[name]));
.replaceWith(j.identifier(replacements[name]));
} else {
root.find(j.Identifier, {name: name})
.replaceWith(j.identifier(requires[name]));
.replaceWith(j.identifier(replacements[name]));
}
});

Expand Down

0 comments on commit ea04523

Please sign in to comment.