Skip to content

Instantly share code, notes, and snippets.

@kcmr
Last active December 28, 2019 23:07
Show Gist options
  • Save kcmr/1258be4499fbb391855a7c9761f67a5c to your computer and use it in GitHub Desktop.
Save kcmr/1258be4499fbb391855a7c9761f67a5c to your computer and use it in GitHub Desktop.
Codemod to replace the first block scope in a file by a IIFE
export default function(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.VariableDeclarator, {
id: {
type: 'Identifier',
name: 'Element',
},
})
.replaceWith(nodePath => {
const { node } = nodePath;
node.id.name = 'PolymerElement';
return node;
})
.toSource();
}
export default function(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.BlockStatement)
.at(0)
.replaceWith(nodePath => {
const nodeValue = nodePath.value;
return j.expressionStatement(
j.callExpression(
j.functionExpression(null, [], j.blockStatement(nodeValue.body)),
[]
)
)
}
)
.toSource();
}
@kcmr
Copy link
Author

kcmr commented Dec 28, 2019

Transforms the following code:

{
  const { Element, html } = Polymer;
}

To:

(function () {
  const { Element, html } = Polymer;
})();

Only the first block statement is replaced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment