docs: update JS/TS docs with package manager instructions, monorepo guide, and troubleshooting

- Fix javascript-installation.mdx: remove references to nonexistent
  codeflash.config.js, use package.json config, fix supported framework
  list (only Jest/Vitest), add Python CLI requirement note
- Add package manager-specific commands (npm/yarn/pnpm/bun) throughout
- Add monorepo setup guide with workspace examples
- Add auto-detection table explaining what codeflash init detects
- Add troubleshooting for common issues (exports, framework detection,
  timeouts, TypeScript, monorepo)
- Add yarn/pnpm CI examples to GitHub Actions page with monorepo tip

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Sarthak Agarwal 2026-03-02 22:10:47 +05:30
parent 3a092a28ba
commit be031ce205
3 changed files with 377 additions and 257 deletions

View file

@ -13,6 +13,7 @@ keywords:
"vitest",
"prettier",
"eslint",
"monorepo",
]
---
@ -40,9 +41,24 @@ Codeflash stores its configuration in `package.json` under the `"codeflash"` key
All file paths are relative to the directory containing `package.json`.
<Info>
Codeflash auto-detects most settings from your project structure. If `codeflash init` produces the right config, you may not need any manual configuration.
Codeflash auto-detects most settings from your project structure. Running `codeflash init` will set up the correct config — manual configuration is usually not needed.
</Info>
## Auto-Detection
When you run `codeflash init`, Codeflash inspects your project and auto-detects:
| Setting | Detection logic |
|---------|----------------|
| `moduleRoot` | Looks for `src/`, `lib/`, or the main source directory |
| `testsRoot` | Looks for `tests/`, `test/`, `__tests__/`, or files matching `*.test.js` / `*.spec.js` |
| `testRunner` | Checks `devDependencies` for `jest` or `vitest` |
| `formatterCmds` | Checks for `prettier`, `eslint`, or `biome` in dependencies and config files |
| Module system | Reads `"type"` field in `package.json` (ESM vs CommonJS) |
| TypeScript | Detects `tsconfig.json` |
You can always override any auto-detected value in the `"codeflash"` section.
## Required Options
- `moduleRoot`: The source directory to optimize. Only code under this directory will be optimized.
@ -87,8 +103,60 @@ No separate configuration is needed for TypeScript vs JavaScript.
| **Jest** | `jest` in dependencies | Default for most projects |
| **Vitest** | `vitest` in dependencies | ESM-native support |
<Info>
**Functions must be exported** to be optimizable. Codeflash uses tree-sitter AST analysis to discover functions and check export status. Supported export patterns:
- `export function foo() {}`
- `export const foo = () => {}`
- `export default function foo() {}`
- `const foo = () => {}; export { foo };`
- `module.exports = { foo }`
- `const utils = { foo() {} }; module.exports = utils;`
</Info>
## Monorepo Configuration
For monorepo projects (Yarn workspaces, pnpm workspaces, Lerna, Nx, Turborepo), configure each package individually:
```text
my-monorepo/
|- packages/
| |- core/
| | |- src/
| | |- tests/
| | |- package.json <-- "codeflash" config here
| |- utils/
| | |- src/
| | |- __tests__/
| | |- package.json <-- "codeflash" config here
|- package.json <-- workspace root (no codeflash config)
```
Run `codeflash init` from within each package:
```bash
cd packages/core
npx codeflash init
```
<Warning>
**Always run codeflash from the package directory**, not the monorepo root. Codeflash needs to find the `package.json` with the `"codeflash"` config in the current working directory.
</Warning>
### Hoisted dependencies
If your monorepo hoists `node_modules` to the root (Yarn Berry with `nodeLinker: node-modules`, pnpm with `shamefully-hoist`), Codeflash resolves modules using Node.js standard resolution. This works automatically.
For **pnpm strict mode** (non-hoisted), ensure `codeflash` is a direct dependency of the package:
```bash
pnpm add --filter @my-org/core --save-dev codeflash
```
## Example
### Standard project
```text
my-app/
|- src/
@ -107,4 +175,46 @@ my-app/
"testsRoot": "tests"
}
}
```
```
### Project with co-located tests
```text
my-app/
|- src/
| |- utils.js
| |- utils.test.js
| |- index.js
|- package.json
```
```json
{
"name": "my-app",
"codeflash": {
"moduleRoot": "src",
"testsRoot": "src"
}
}
```
### CommonJS library with no separate test directory
```text
my-lib/
|- lib/
| |- helpers.js
|- test/
| |- helpers.spec.js
|- package.json
```
```json
{
"name": "my-lib",
"codeflash": {
"moduleRoot": "lib",
"testsRoot": "test"
}
}
```

View file

@ -1,38 +1,51 @@
---
title: "JavaScript Installation"
title: "JavaScript / TypeScript Installation"
description: "Install and configure Codeflash for your JavaScript/TypeScript project"
icon: "node-js"
keywords:
[
"installation",
"javascript",
"typescript",
"npm",
"yarn",
"pnpm",
"bun",
"jest",
"vitest",
"monorepo",
]
---
Codeflash now supports JavaScript and TypeScript projects with optimized test data serialization using V8 native serialization.
Codeflash supports JavaScript and TypeScript projects. It uses V8 native serialization for test data capture and works with Jest and Vitest test frameworks.
### Prerequisites
Before installing Codeflash for JavaScript, ensure you have:
Before installing Codeflash, ensure you have:
1. **Node.js 16 or above** installed
1. **Node.js 18 or above** installed
2. **A JavaScript/TypeScript project** with a package manager (npm, yarn, pnpm, or bun)
3. **Project dependencies installed**
Good to have (optional):
1. **Unit Tests** that Codeflash uses to ensure correctness of the optimizations
1. **Unit tests** (Jest or Vitest) — Codeflash uses them to verify correctness of optimizations
<Warning>
**Node.js Runtime Required**
**Node.js 18+ Required**
Codeflash JavaScript support uses V8 serialization API, which is available natively in Node.js. Make sure you're running on Node.js 16+ for optimal compatibility.
Codeflash requires Node.js 18 or above. Check your version:
```bash
node --version # Should show v16.0.0 or higher
node --version # Should show v18.0.0 or higher
```
</Warning>
<Steps>
<Step title="Install Codeflash CLI">
<Step title="Install the Codeflash npm package">
Install Codeflash globally or as a development dependency in your project:
Install Codeflash as a development dependency in your project:
<CodeGroup>
```bash npm
@ -50,321 +63,285 @@ pnpm add --save-dev codeflash
```bash bun
bun add --dev codeflash
```
```bash global
npm install -g codeflash
```
</CodeGroup>
<Tip>
**Development Dependency Recommended**
Codeflash is intended for development and CI workflows. Installing as a dev dependency keeps your production bundle clean.
**Dev dependency recommended** — Codeflash is for development and CI workflows. Installing as a dev dependency keeps your production bundle clean.
</Tip>
<Info>
**Codeflash also requires a Python installation** (3.9+) to run the CLI optimizer. Install the Python CLI globally:
```bash
pip install codeflash
# or
uv tool install codeflash
```
The Python CLI orchestrates the optimization pipeline, while the npm package provides the JavaScript runtime (test runners, serialization, reporters).
</Info>
</Step>
<Step title="Generate a Codeflash API Key">
Codeflash uses cloud-hosted AI models. You need an API key:
1. Visit the [Codeflash Web App](https://app.codeflash.ai/)
2. Sign up with your GitHub account (free tier available)
3. Navigate to the [API Key](https://app.codeflash.ai/app/apikeys) page to generate your key
Set it as an environment variable:
```bash
export CODEFLASH_API_KEY="your-api-key-here"
```
Or add it to your shell profile (`~/.bashrc`, `~/.zshrc`) for persistence.
</Step>
<Step title="Run Automatic Configuration">
Navigate to your project's root directory (where your `package.json` file is) and run:
Navigate to your project root (where `package.json` is) and run:
```bash
<CodeGroup>
```bash npm / yarn / pnpm
npx codeflash init
```
```bash bun
bunx codeflash init
```
```bash Global install
codeflash init
```
</CodeGroup>
When running `codeflash init`, you will see the following prompts:
### What `codeflash init` does
```text
1. Enter your Codeflash API key (or login with Codeflash)
2. Which JavaScript/TypeScript module do you want me to optimize? (e.g. src/)
3. Where are your tests located? (e.g. tests/, __tests__/, *.test.js)
4. Which test framework do you use? (jest/vitest/mocha/ava/other)
5. Which code formatter do you use? (prettier/eslint/biome/disabled)
6. Which git remote should Codeflash use for Pull Requests? (if multiple remotes exist)
7. Help us improve Codeflash by sharing anonymous usage data?
8. Install the GitHub app
9. Install GitHub actions for Continuous optimization?
Codeflash **auto-detects** most settings from your project:
| Setting | How it's detected |
|---------|------------------|
| **Module root** | Looks for `src/`, `lib/`, or the directory containing your source files |
| **Tests root** | Looks for `tests/`, `test/`, `__tests__/`, or files matching `*.test.js` / `*.spec.js` |
| **Test framework** | Checks `devDependencies` for `jest` or `vitest` |
| **Formatter** | Checks for `prettier`, `eslint`, or `biome` in dependencies and config files |
| **Module system** | Reads `"type"` field in `package.json` (ESM vs CommonJS) |
| **TypeScript** | Detects `tsconfig.json` presence |
You'll be prompted to confirm or override the detected values. The configuration is saved in your `package.json` under the `"codeflash"` key:
```json
{
"name": "my-project",
"codeflash": {
"moduleRoot": "src",
"testsRoot": "tests"
}
}
```
After you have answered these questions, the Codeflash configuration will be saved in a `codeflash.config.js` file.
<Info>
**Test Data Serialization Strategy**
Codeflash uses **V8 serialization** for JavaScript test data capture. This provides:
- ⚡ **Best performance**: 2-3x faster than alternatives
- 🎯 **Perfect type preservation**: Maintains Date, Map, Set, TypedArrays, and more
- 📦 **Compact binary storage**: Smallest file sizes
- 🔄 **Framework agnostic**: Works with React, Vue, Angular, Svelte, and vanilla JS
**No separate config file needed.** Codeflash stores all configuration inside your existing `package.json`, not in a separate config file.
</Info>
</Step>
<Step title="Generate a Codeflash API Key">
Codeflash uses cloud-hosted AI models and integrations with GitHub. If you haven't created one already, you'll need to create an API key to authorize your access.
<Step title="Install the Codeflash GitHub App (optional)">
1. Visit the [Codeflash Web App](https://app.codeflash.ai/)
2. Sign up with your GitHub account (free)
3. Navigate to the [API Key](https://app.codeflash.ai/app/apikeys) page to generate your API key
To receive optimization PRs automatically, install the Codeflash GitHub App:
<Note>
**Free Tier Available**
[Install Codeflash GitHub App](https://github.com/apps/codeflash-ai/installations/select_target)
Codeflash offers a **free tier** with a limited number of optimizations. Perfect for trying it out on small projects!
</Note>
</Step>
<Step title="Install the Codeflash GitHub App">
Finally, if you have not done so already, Codeflash will ask you to install the GitHub App in your repository.
The Codeflash GitHub App allows the codeflash-ai bot to open PRs, review code, and provide optimization suggestions.
Please [install the Codeflash GitHub
app](https://github.com/apps/codeflash-ai/installations/select_target) by choosing the repository you want to install
Codeflash on.
This enables the codeflash-ai bot to open PRs with optimization suggestions. If you skip this step, you can still optimize locally using `--no-pr`.
</Step>
</Steps>
## Framework Support
## Monorepo Setup
Codeflash JavaScript support works seamlessly with all major frameworks and testing libraries:
For monorepos (Yarn workspaces, pnpm workspaces, Lerna, Nx, Turborepo), run `codeflash init` from within each package you want to optimize:
<CardGroup cols={2}>
<Card title="Frontend Frameworks" icon="react">
- React
- Vue.js
- Angular
- Svelte
- Solid.js
</Card>
```bash
# Navigate to the specific package
cd packages/my-library
<Card title="Test Frameworks" icon="flask">
- Jest
- Vitest
- Mocha
- AVA
- Playwright
- Cypress
</Card>
# Run init from the package directory
npx codeflash init
```
<Card title="Backend" icon="server">
- Express
- NestJS
- Fastify
- Koa
- Hono
</Card>
Each package gets its own `"codeflash"` section in its `package.json`. The `moduleRoot` and `testsRoot` paths are relative to that package's `package.json`.
<Card title="Runtimes" icon="gears">
- Node.js ✅ (Recommended)
- Bun (Coming soon)
- Deno (Coming soon)
</Card>
</CardGroup>
### Example: Yarn workspaces monorepo
## Understanding V8 Serialization
```text
my-monorepo/
|- packages/
| |- core/
| | |- src/
| | |- tests/
| | |- package.json <-- codeflash config here
| |- utils/
| | |- src/
| | |- __tests__/
| | |- package.json <-- codeflash config here
|- package.json <-- root workspace (no codeflash config needed)
```
Codeflash uses Node.js's native V8 serialization API to capture and compare test data. Here's what makes it powerful:
### Type Preservation
Unlike JSON serialization, V8 serialization preserves JavaScript-specific types:
```javascript
// These types are preserved perfectly:
const testData = {
date: new Date(), // ✅ Date objects
map: new Map([['key', 'value']]), // ✅ Map instances
set: new Set([1, 2, 3]), // ✅ Set instances
buffer: Buffer.from('hello'), // ✅ Buffers
typed: new Uint8Array([1, 2, 3]), // ✅ TypedArrays
bigint: 9007199254740991n, // ✅ BigInt
regex: /pattern/gi, // ✅ RegExp
undef: undefined, // ✅ undefined (not null!)
circular: {} // ✅ Circular references
};
testData.circular.self = testData.circular;
```json
// packages/core/package.json
{
"name": "@my-org/core",
"codeflash": {
"moduleRoot": "src",
"testsRoot": "tests"
}
}
```
<Warning>
**Why Not JSON?**
JSON serialization would cause bugs to slip through:
- `Date` becomes string → date arithmetic fails silently
- `Map` becomes `{}` → `.get()` calls return undefined
- `undefined` becomes `null` → type checks break
- TypedArrays become plain objects → binary operations fail
V8 serialization catches these issues during optimization verification.
**Run codeflash from the package directory**, not the monorepo root. Codeflash needs to find the `package.json` with the `"codeflash"` config in the current working directory.
</Warning>
## Try It Out!
<Info>
**Hoisted dependencies work fine.** If your monorepo hoists `node_modules` to the root (common in Yarn Berry, pnpm with `shamefully-hoist`), Codeflash resolves modules using Node.js standard resolution and will find them correctly.
</Info>
<Tabs>
<Tab title="Quick Start">
Once configured, you can start optimizing your JavaScript/TypeScript code immediately:
## Test Framework Support
```bash
# Optimize a specific function
codeflash --file path/to/your/file.js --function functionName
| Framework | Status | Auto-detected from |
|-----------|--------|-------------------|
| **Jest** | Supported | `jest` in dependencies |
| **Vitest** | Supported | `vitest` in dependencies |
| **Mocha** | Coming soon | — |
# Or optimize all functions in your codebase
<Info>
**Functions must be exported** to be optimizable. Codeflash can only discover and optimize functions that are exported from their module (via `export`, `export default`, or `module.exports`).
</Info>
## Try It Out
Once configured, optimize your code:
<CodeGroup>
```bash Optimize a function
codeflash --file src/utils.js --function processData
```
```bash Optimize locally (no PR)
codeflash --file src/utils.ts --function processData --no-pr
```
```bash Optimize entire codebase
codeflash --all
```
</Tab>
<Tab title="TypeScript Support">
Codeflash fully supports TypeScript projects:
```bash
# Optimize TypeScript files directly
codeflash --file src/utils.ts --function processData
# Works with TSX for React components
codeflash --file src/components/DataTable.tsx --function DataTable
```bash Trace and optimize
codeflash optimize --jest
```
<Info>
Codeflash preserves TypeScript types during optimization. Your type annotations and interfaces remain intact.
</Info>
</Tab>
<Tab title="Test Framework Examples">
<Accordion title="Jest Example">
```javascript
// sum.test.js
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
// Optimize the sum function
codeflash --file sum.js --function sum
```
</Accordion>
<Accordion title="Vitest Example">
```javascript
// calculator.test.js
import { describe, it, expect } from 'vitest';
describe('calculator', () => {
it('should multiply correctly', () => {
expect(multiply(2, 3)).toBe(6);
});
});
// Optimize the multiply function
codeflash --file calculator.js --function multiply
```
</Accordion>
</Tab>
</Tabs>
</CodeGroup>
## Troubleshooting
<AccordionGroup>
<Accordion title="📦 Module not found errors">
Make sure:
- ✅ All project dependencies are installed
- ✅ Your `node_modules` directory exists
<Accordion title="Function not found or not exported">
Codeflash only optimizes **exported** functions. Make sure your function is exported:
```bash
# Reinstall dependencies
npm install
# or
yarn install
```
</Accordion>
<Accordion title="🔧 V8 serialization errors">
If you encounter serialization errors:
**Functions and classes** cannot be serialized:
```javascript
// ❌ Won't work - contains function
const data = { callback: () => {} };
// ES Modules
export function processData(data) { ... }
// or
const processData = (data) => { ... };
export { processData };
// ✅ Works - pure data
const data = { value: 42, items: [1, 2, 3] };
// CommonJS
function processData(data) { ... }
module.exports = { processData };
```
**Symbols** are not serializable:
```javascript
// ❌ Won't work
const data = { [Symbol('key')]: 'value' };
// ✅ Use string keys
const data = { key: 'value' };
```
If codeflash reports the function exists but is not exported, add an export statement.
</Accordion>
<Accordion title="🧪 No optimizations found">
Not all functions can be optimized - some code is already optimal. This is expected.
<Accordion title="codeflash npm package not found / module errors">
Ensure the codeflash npm package is installed in your project:
Use the `--verbose` flag for detailed output:
```bash
codeflash optimize --verbose
<CodeGroup>
```bash npm
npm install --save-dev codeflash
```
```bash yarn
yarn add --dev codeflash
```
```bash pnpm
pnpm add --save-dev codeflash
```
</CodeGroup>
This will show:
- 🔍 Which functions are being analyzed
- 🚫 Why certain functions were skipped
- ⚠️ Detailed error messages
- 📊 Performance analysis results
For **monorepos**, make sure it's installed in the package you're optimizing, or at the workspace root if dependencies are hoisted.
</Accordion>
<Accordion title="🔍 Test discovery issues">
Verify:
- 📁 Your test directory path is correct in `codeflash.config.js`
- 🔍 Tests are discoverable by your test framework
- 📝 Test files follow naming conventions (`*.test.js`, `*.spec.js`)
<Accordion title="Test framework not detected">
Codeflash auto-detects the test framework from your `devDependencies`. If detection fails:
1. Verify your test framework is in `devDependencies`:
```bash
npm ls jest # or: npm ls vitest
```
2. Or set it manually in `package.json`:
```json
{
"codeflash": {
"testRunner": "jest"
}
}
```
</Accordion>
<Accordion title="Jest tests timing out">
If Jest tests take too long, Codeflash has a default timeout. For large test suites:
- Use `--file` and `--function` to target specific functions instead of `--all`
- Ensure your tests don't have expensive setup/teardown that runs for every test file
- Check if `jest.config.js` has a `setupFiles` that takes a long time
</Accordion>
<Accordion title="TypeScript compilation errors">
Codeflash uses your project's TypeScript configuration. If you see TS errors:
1. Verify `npx tsc --noEmit` passes on its own
2. Check that `tsconfig.json` is in the project root or the module root
3. For projects using `moduleResolution: "bundler"`, Codeflash creates a temporary tsconfig overlay — this is expected behavior
</Accordion>
<Accordion title="Monorepo: wrong package.json detected">
Run codeflash from the correct package directory:
```bash
# Test if your test framework can discover tests
npm test -- --listTests # Jest
# or
npx vitest list # Vitest
cd packages/my-library
codeflash --file src/utils.ts --function myFunc
```
If your monorepo tool hoists dependencies, you may need to ensure the `codeflash` npm package is accessible from the package directory. For pnpm, add `.npmrc` with `shamefully-hoist=true` or use `pnpm add --filter my-library --save-dev codeflash`.
</Accordion>
<Accordion title="No optimizations found">
Not all functions can be optimized — some code is already efficient. This is normal.
For better results:
- Target functions with loops, string manipulation, or data transformations
- Ensure the function has existing tests for correctness verification
- Use `codeflash optimize --jest` to trace real execution and capture realistic inputs
</Accordion>
</AccordionGroup>
## Configuration
## Configuration Reference
Your `codeflash.config.js` file controls how Codeflash analyzes your JavaScript project:
```javascript
module.exports = {
// Source code to optimize
module: 'src',
// Test location
tests: 'tests',
// Test framework
testFramework: 'jest',
// Serialization strategy (automatically set to 'v8')
serialization: 'v8',
// Formatter
formatter: 'prettier',
// Additional options
exclude: ['node_modules', 'dist', 'build'],
verbose: false
};
```
See [JavaScript / TypeScript Configuration](/configuration/javascript) for the full list of options.
### Next Steps
- Learn about [Codeflash Concepts](/codeflash-concepts/how-codeflash-works)
- Explore [Optimization workflows](/optimizing-with-codeflash/one-function)
- Learn [how Codeflash works](/codeflash-concepts/how-codeflash-works)
- [Optimize a single function](/optimizing-with-codeflash/one-function)
- Set up [Pull Request Optimization](/optimizing-with-codeflash/codeflash-github-actions)
- Read [configuration options](/configuration) for advanced setups
- Explore [Trace and Optimize](/optimizing-with-codeflash/trace-and-optimize) for workflow optimization

View file

@ -161,7 +161,40 @@ be copied.
- name: Run Codeflash to optimize code
run: npx codeflash
```
```yaml yarn (JavaScript/TypeScript)
- uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install Project Dependencies
run: yarn install --immutable
- name: Run Codeflash to optimize code
run: yarn codeflash
```
```yaml pnpm (JavaScript/TypeScript)
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'pnpm'
- name: Install Project Dependencies
run: pnpm install --frozen-lockfile
- name: Run Codeflash to optimize code
run: pnpm codeflash
```
</CodeGroup>
<Info>
**Monorepo?** If your codeflash config is in a subdirectory, add `working-directory` to the steps:
```yaml
- name: Run Codeflash to optimize code
run: npx codeflash
working-directory: packages/my-library
```
</Info>
</Step>
<Step title="Add Repository Secret">