Last active
February 9, 2022 12:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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