🌿 Pure Index
Pure Index is utility for monorepos. It helps to find unused exports from packages.
Motivation
There is a package a
which exports 2 functions
export const T = () => true
export { myFn } from './myFn'
only 1 function from the package is used in the project
import { T } from 'a'
This means that package a
exports myFn
for nothing, so we can remove its export and possibly remove all the code.
As the code base develops, a large number of such unnecessary exports may accumulate in the monorepo. Pure Index allows you to find such exports.
Usage
- Install
npm install --save-dev pure-index
- Add the
check-exports
script in the package.json
of each package that needs to be checked
"scripts": {
"build": "webpack ./webpack.config.js",
+ "check-exports": "pure-index",
"test": "vitest"
}
- Configure
Config
Pure Index supports two ways to define config.
.pure-index.json
config file:
{
"entry": "index.ts",
"exclude": ["node_modules"],
"babelPlugins": ["typescript"],
"batch": {
"default": 100
}
}
- or
pure-index
section in package.json
:
"pure-index": {
"entry": "index.ts",
"exclude": ["node_modules"],
"babelPlugins": ["typescript"],
"batch": {
"default": 100
}
}
Arguments
entry (String)
— path to the package index file. relative to the package directory.exclude (Array<string>)
— list of directories that will be excluded when searching for imports.babelPlugins (Array<string>)
— list of babel plugins that will be used when parsing files.batch.default (Number)
— number of files to be traversed in parallel. changing the value may speed up or slow down the script. choose the value yourself.
Explanation
How It Works
In fact, the task is to compare all exports and imports of the package. Anything not imported but exported are unused exports.
Base algorithm:
- collect all package exports into exports Set
- traverse all files where package import may occur
- if import is found, remove it from exports Set
- if the size of exports exports Set became equal to 0, then exit with success
- if exports Set size is not equal to 0, then exit with an error
How It Optimized
- file reading is divided into batches
- file is not immediately converted to AST. First the import of the package is searched for in the file. createReadStream is used
- there is an instant exit with success as soon as the size of exports Set is equal to zero