Babel plugin that transforms eval() calls containing string literals by parsing and compiling the string content at transform time
Overall
score
98%
Build a Babel plugin that analyzes JavaScript code and removes unreachable dead code based on compile-time evaluation of conditional expressions.
Your task is to implement a Babel plugin that identifies and eliminates dead code branches in if statements where the condition can be statically evaluated to a constant boolean value at compile time. The plugin should evaluate simple expressions and remove unreachable code paths.
Your plugin should handle the following scenarios:
if statements with boolean literal conditions1 > 2, 5 === 5) at compile timeif (2 + 2 === 4))true, remove the else branchfalse, remove the if branch and keep only the else branch contenttrue, replace the entire if statement with just the consequent block's statementsfalse and there is no else branch, remove the entire if statementfalse and there is an else branch, replace the entire if statement with the alternate block's statementsThe following test cases should pass:
if (true) should keep only the consequent statements @test// Input
if (true) {
console.log("always runs");
} else {
console.log("never runs");
}
// Expected output
console.log("always runs");if (false) should remove the if statement entirely or keep only else branch @test// Input
if (false) {
console.log("never runs");
} else {
console.log("always runs");
}
// Expected output
console.log("always runs");// Input
if (5 > 10) {
console.log("dead code");
} else {
console.log("this remains");
}
// Expected output
console.log("this remains");// Input
const x = 5;
if (x > 10) {
console.log("maybe");
}
// Expected output (unchanged)
const x = 5;
if (x > 10) {
console.log("maybe");
}@generates
/**
* Dead Code Eliminator Plugin
*
* A Babel plugin that removes unreachable code based on static analysis
* of conditional expressions.
*
* @returns {Object} Babel plugin object with visitor methods
*/
module.exports = function() {
return {
visitor: {
// Your implementation here
}
};
};Provides the core Babel transformation APIs.
Provides AST traversal utilities and the visitor pattern.
Provides utilities for AST node type checking and manipulation.
Install with Tessl CLI
npx tessl i tessl/npm-babel-plugin-transform-evaldocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10