Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Remove redundant use strict (Fix #542)
- Loading branch information
Showing
3 changed files
with
93 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
56 changes: 56 additions & 0 deletions
56
packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
"use strict"; | ||
|
||
module.exports = removeUseStrict; | ||
|
||
const newIssueUrl = "https://github.com/babel/babili/issues/new"; | ||
|
||
const useStrict = "use strict"; | ||
|
||
/** | ||
* Remove redundant use strict | ||
* If the parent has a "use strict" directive, it is not required in | ||
* the children | ||
* | ||
* @param {NodePath} block BlockStatement | ||
*/ | ||
function removeUseStrict(block) { | ||
if (!block.isBlockStatement()) { | ||
throw new Error( | ||
`Received ${block.type}. Expected BlockStatement. ` + | ||
`Please report at ${newIssueUrl}` | ||
); | ||
} | ||
|
||
const useStricts = getUseStrictDirectives(block); | ||
|
||
// early exit | ||
if (useStricts.length < 1) return; | ||
|
||
// only keep the first use strict | ||
if (useStricts.length > 1) { | ||
for (let i = 1; i < useStricts.length; i++) { | ||
useStricts[i].remove(); | ||
} | ||
} | ||
|
||
// check if parent has an use strict | ||
if (hasStrictParent(block)) { | ||
useStricts[0].remove(); | ||
} | ||
} | ||
|
||
function hasStrictParent(path) { | ||
return path.findParent( | ||
parent => parent.isBlockStatement() && isStrict(parent) | ||
); | ||
} | ||
|
||
function isStrict(block) { | ||
return getUseStrictDirectives(block).length > 0; | ||
} | ||
|
||
function getUseStrictDirectives(block) { | ||
return block.get("directives").filter(directive => { | ||
return directive.node.value.value === useStrict; | ||
}); | ||
} |