Skip to content

pcattori/babel-dead-code-elimination

Repository files navigation

babel-dead-code-elimination

Composable primitives for dead code elimination in Babel

This package is not a Babel plugin, but rather a set of composable primitives to author your own Babel transforms and plugins.

Install

npm install babel-dead-code-elimination

deadCodeElimination

Eliminates unused code from the Babel AST by repeatedly removing unreferenced identifiers.

import { parse } from "@babel/parser"
import generate from "@babel/generator"

import { deadCodeElimination } from "babel-dead-code-elimination"

let source = "..."
let ast = parse(source, { sourceType: "module" })
deadCodeElimination(ast)
let result = generate(ast).code

findReferencedIdentifiers

Find identifiers that are currently referenced in the Babel AST.

Useful for limiting deadCodeElimination to only eliminate newly unreferenced identifiers, as a best effort to preserve any intentional side-effects in the source.

import { parse } from "@babel/parser"
import generate from "@babel/generator"
import traverse from "@babel/traverse"

import {
  deadCodeElimination,
  findReferencedIdentifiers,
} from "babel-dead-code-elimination"

let source = "..."
let ast = parse(source, { sourceType: "module" })
let referenced = findReferencedIdentifiers(ast)

traverse(ast, {
  /* ... your custom transform goes here ... */
})

deadCodeElimination(ast, referenced)
let result = generate(ast).code

Prior art

Credit to Jason Miller for the initial implementation. Thanks to these projects for exploring dead code elimination:

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published