Skip to content

Instantly share code, notes, and snippets.

@devnoname120
Last active November 26, 2024 08:21
Show Gist options
  • Save devnoname120/8067fe0f10df2e616312931b243f5b87 to your computer and use it in GitHub Desktop.
Save devnoname120/8067fe0f10df2e616312931b243f5b87 to your computer and use it in GitHub Desktop.
Front — Fix circular dependencies
// Note: this replaces module.exports = ... with something like Object.assign(module.exports, AnalyticsSavedViewResource)
// This doesn't work but this was a worthwhile experiment and we can reuse this code as a base.
module.exports = function (file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
fixTopLevelAssignments(j, root);
fixTopLevelChainedAssignments(j, root);
return root.toSource({quote: 'single'});
};
function fixTopLevelAssignments(j, root) {
const expressionsToFix = root.find(j.ExpressionStatement, {
expression : {
type: 'AssignmentExpression',
operator: '=',
left: {
type: 'MemberExpression',
object: {
name: 'module',
type: 'Identifier'
},
property: {
name: 'exports',
type: 'Identifier'
}
}
}
});
expressionsToFix.forEach(p => {
const callExpression = j.callExpression(
j.memberExpression(j.identifier('Object'), j.identifier('assign')),
[
j.memberExpression(j.identifier('module'), j.identifier('exports')),
p.value.expression.right
]
);
const expressionStatement = j.expressionStatement(callExpression);
j(p).replaceWith(expressionStatement);
});
}
function fixTopLevelChainedAssignments(j, root) {
const expressionsToFix = root.find(j.VariableDeclaration, {
declarations: [{
type: 'VariableDeclarator',
init: {
type: 'AssignmentExpression',
operator: '=',
left: {
type: 'MemberExpression',
object: {
name: 'module',
type: 'Identifier'
},
property: {
name: 'exports',
type: 'Identifier'
}
}
}
}]
}).filter(p => p.value.declarations.length === 1);
expressionsToFix.forEach(p => {
const declPath = p.get('declarations').get(0).get('init');
j(declPath).replaceWith(p.value.declarations[0].init.right);
const callExpression = j.callExpression(
j.memberExpression(j.identifier('Object'), j.identifier('assign')),
[
j.memberExpression(j.identifier('module'), j.identifier('exports')),
p.value.declarations[0].id
]
);
const expressionStatement = j.expressionStatement(callExpression);
j(p).insertAfter(expressionStatement);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment