Skip to content

Instantly share code, notes, and snippets.

@binki
Last active February 9, 2022 12:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binki/6708214fda882bbd5b0412ba55676728 to your computer and use it in GitHub Desktop.
Save binki/6708214fda882bbd5b0412ba55676728 to your computer and use it in GitHub Desktop.
jscodeshift codemod to add "use strict" to any file where it is not already the first statement
module.exports = function (fileInfo, {
jscodeshift,
}, options) {
// Work around for https://github.com/facebook/jscodeshift/issues/262
const isUnix = fileInfo.source.indexOf('\r\n') === -1;
const dom = jscodeshift(fileInfo.source);
const topLevelStatements = jscodeshift(dom.get('program', 'body').value).filter(path => {
return jscodeshift.Statement.check(path.node);
});
// Don’t add another one if it is already there.
if (topLevelStatements.length > 0 && isUseStrictStatement(topLevelStatements.get(0).node)) {
return;
}
dom.get('program', 'body').unshift(jscodeshift.expressionStatement(jscodeshift.literal('use strict')));
return dom.toSource().replace(/\r\n/g, isUnix ? '\n' : '\r\n');
function isUseStrictStatement(node) {
return jscodeshift.ExpressionStatement.check(node)
&& jscodeshift.Literal.check(node.expression)
&& node.expression.value === 'use strict';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment