istanbul-lib-instrument serves as the core engine within the Istanbul.js ecosystem for transforming JavaScript source code into an instrumented form suitable for code coverage analysis. It injects tracking statements (for lines, functions, branches, and statements) into code. The library, currently at version 6.0.3 (released June 2024), is an active component of the `istanbuljs` monorepo, which receives regular updates across its packages to support modern JavaScript features and tooling. Its key differentiator is its reliance on Babel for its instrumentation process, providing two primary modes of operation: a direct programmatic API for straightforward source code transformation, and a `programVisitor` function designed for seamless integration within custom Babel plugins, which is the recommended approach for developers already utilizing Babel in their build pipelines.
npm install istanbul-lib-instrumentVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `createInstrumenter` and `instrumentSync` to programmatically instrument a JavaScript string, generate source maps, and log the resulting instrumented code. It also highlights options for customizing the instrumentation process.
Review `v0-changes.md` for specific migration steps. Update your codebase to align with Babel-based instrumentation practices, particularly if you were accessing internal APIs or custom parser options.
Ensure you are using the latest stable version of `istanbul-lib-instrument` (>=6.0.3 for `importAttributes` support). If using `programVisitor` with your own Babel setup, ensure your Babel configuration includes all necessary plugins to parse your source code.
Always pass a valid `inputSourceMap` to `instrumentSync` if your code is already transpiled. Ensure your build process is correctly configured to generate and pass through source maps at each transformation step. Validate source map chains with tools like `source-map-explorer`.
Update `istanbul-lib-instrument` to its latest version to ensure support for newer JavaScript syntax. If using the `programVisitor` with your own Babel setup, verify that your Babel configuration (especially `parserPlugins`) includes the necessary plugins for the syntax in your source code.
Before executing instrumented code, ensure the global coverage object is defined. In Node.js, `global.__coverage__ = {};`. In browsers, `window.__coverage__ = {};`. Confirm the `coverageVariable` option used during instrumentation matches the variable you are checking.