Skip to content

Instantly share code, notes, and snippets.

@bgando
Last active December 13, 2017 22:28
Show Gist options
  • Save bgando/31cd668b6631d6f828410c5100c2c3cc to your computer and use it in GitHub Desktop.
Save bgando/31cd668b6631d6f828410c5100c2c3cc to your computer and use it in GitHub Desktop.
Codemod to convert x.viewModel() to canViewModel(x) and add var canViewModel = require('can-view-model');
export default function(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
const removeViewModel = p => {
if (p.node.expression.type === 'CallExpression' && p.node.expression.callee.property && p.node.expression.callee.property.name === 'viewModel') {
p.node.expression = p.node.expression.callee.object;
var ast = j.callExpression(j.identifier('canViewModel'), [p.node.expression]);
p.node.expression = ast;
addNodeToBody(node)
}
};
const addNodeToBody = node => root.find(j.Program).get('body').value.unshift(node);
const constructNode = () => {
const requireStatement = j.callExpression(j.identifier('require'), [j.literal('can-view-model')])
const variableName = j.variableDeclarator(j.identifier('canViewModel'), requireStatement);
return j.variableDeclaration('var', [variableName])
}
const node = constructNode();
return root
.find(j.ExpressionStatement)
.forEach(removeViewModel)
.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment