blazeofchi/pdf-ocr-rl-qwen3vl2b-sft-grpo
Image-Text-to-Text • Updated
• 11
image imagewidth (px) 1.24k 1.24k | markdown stringlengths 200 5.91k | language stringclasses 2 values | source stringclasses 2 values | doc_id stringclasses 757 values | page_num int32 0 51 |
|---|---|---|---|---|---|
# React Compiler Passes Documentation
This directory contains detailed documentation for each pass in the React Compiler pipeline. The compiler transforms React components and hooks to add automatic memoization.
## High-Level Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ COMPILATION PIPELINE │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 1: HIR CONSTRUCTION │
│ ┌─────────┐ │
│ │ Babel │──▶ lower ──▶ enterSSA ──▶ eliminateRedundantPhi │
│ │ AST │ │ │
│ └─────────┘ ▼ │
│ ┌──────────┐ │
│ │ HIR │ (Control Flow Graph in SSA Form) │
│ └──────────┘ │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 2: OPTIMIZATION │
│ │
│ constantPropagation ──▶ deadCodeElimination │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
| en | en | en_0000_README | 0 | |
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 3: TYPE & EFFECT INFERENCE │
│ │
│ inferTypes ──▶ analyseFunctions ──▶ inferMutationAliasingEffects │
│ │ │
│ ▼ │
│ inferMutationAliasingRanges ──▶ inferReactivePlaces │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 4: REACTIVE SCOPE CONSTRUCTION │
│ │
│ inferReactiveScopeVariables ──▶ alignMethodCallScopes ──▶ alignObjectMethodScopes │
│ │ │
│ ▼ │
│ alignReactiveScopesToBlockScopesHIR ──▶ mergeOverlappingReactiveScopesHIR │
│ │ │
│ ▼ │
│ buildReactiveScopeTerminalsHIR ──▶ flattenReactiveLoopsHIR │
│ │ │
│ | en | en | en_0000_README | 1 | |
▼ │
│ flattenScopesWithHooksOrUseHIR ──▶ propagateScopeDependenciesHIR │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 5: HIR → REACTIVE FUNCTION │
│ │
│ buildReactiveFunction │
│ │ │
│ ▼ │
│ ┌───────────────────┐ │
│ │ ReactiveFunction │ (Tree Structure) │
│ └───────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 6: REACTIVE FUNCTION OPTIMIZATION │
│ │
│ pruneUnusedLabels ──▶ pruneNonEscapingScopes ──▶ pruneNonReactiveDependencies │
│ │ │
│ ▼ │
│ | en | en | en_0000_README | 2 | |
pruneUnusedScopes ──▶ mergeReactiveScopesThatInvalidateTogether │
│ │ │
│ ▼ │
│ pruneAlwaysInvalidatingScopes ──▶ propagateEarlyReturns ──▶ promoteUsedTemporaries │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ PHASE 7: CODE GENERATION │
│ │
│ renameVariables ──▶ codegenReactiveFunction │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Babel AST │ (With Memoization) │
│ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
```
## Pass Categories
### HIR Construction & SSA (1-3)
| # | Pass | File | Description |
|---|------|------|-------------|
| 1 | [lower](01-lower.md) | `HIR/BuildHIR.ts` | Convert Babel AST to HIR control-flow graph |
| 2 | [enterSSA](02-enterSSA.md) | `SSA/EnterSSA.ts` | Convert to Static Single Assignment form |
| 3 | [eliminateRedundantPhi](03-eliminateRedundantPhi.md) | `SSA/EliminateRedundantPhi.ts` | Remove unnecessary phi nodes |
### Optimization (4-5)
| en | en | en_0000_README | 3 | |
| # | Pass | File | Description |
|---|------|------|-------------|
| 4 | [constantPropagation](04-constantPropagation.md) | `Optimization/ConstantPropagation.ts` | Sparse conditional constant propagation |
| 5 | [deadCodeElimination](05-deadCodeElimination.md) | `Optimization/DeadCodeElimination.ts` | Remove unreferenced instructions |
### Type Inference (6)
| # | Pass | File | Description |
|---|------|------|-------------|
| 6 | [inferTypes](06-inferTypes.md) | `TypeInference/InferTypes.ts` | Constraint-based type unification |
### Mutation/Aliasing Inference (7-10)
| # | Pass | File | Description |
|---|------|------|-------------|
| 7 | [analyseFunctions](07-analyseFunctions.md) | `Inference/AnalyseFunctions.ts` | Analyze nested function effects |
| 8 | [inferMutationAliasingEffects](08-inferMutationAliasingEffects.md) | `Inference/InferMutationAliasingEffects.ts` | Infer mutation/aliasing via abstract interpretation |
| 9 | [inferMutationAliasingRanges](09-inferMutationAliasingRanges.md) | `Inference/InferMutationAliasingRanges.ts` | Compute mutable ranges from effects |
| 10 | [inferReactivePlaces](10-inferReactivePlaces.md) | `Inference/InferReactivePlaces.ts` | Mark reactive places (props, hooks, derived) |
### Reactive Scope Variables (11-12)
| # | Pass | File | Description |
|---|------|------|-------------|
| 11 | [inferReactiveScopeVariables](11-inferReactiveScopeVariables.md) | `ReactiveScopes/InferReactiveScopeVariables.ts` | Group co-mutating variables into scopes |
| 12 | [rewriteInstructionKindsBasedOnReassignment](12-rewriteInstructionKindsBasedOnReassignment.md) | `SSA/RewriteInstructionKindsBasedOnReassignment.ts` | Convert SSA loads to context loads for reassigned vars |
### Scope Alignment (13-15)
| en | en | en_0000_README | 4 | |
| # | Pass | File | Description |
|---|------|------|-------------|
| 13 | [alignMethodCallScopes](13-alignMethodCallScopes.md) | `ReactiveScopes/AlignMethodCallScopes.ts` | Align method call scopes with receivers |
| 14 | [alignObjectMethodScopes](14-alignObjectMethodScopes.md) | `ReactiveScopes/AlignObjectMethodScopes.ts` | Align object method scopes |
| 15 | [alignReactiveScopesToBlockScopesHIR](15-alignReactiveScopesToBlockScopesHIR.md) | `ReactiveScopes/AlignReactiveScopesToBlockScopesHIR.ts` | Align to control-flow block boundaries |
### Scope Construction (16-18)
| # | Pass | File | Description |
|---|------|------|-------------|
| 16 | [mergeOverlappingReactiveScopesHIR](16-mergeOverlappingReactiveScopesHIR.md) | `HIR/MergeOverlappingReactiveScopesHIR.ts` | Merge overlapping scopes |
| 17 | [buildReactiveScopeTerminalsHIR](17-buildReactiveScopeTerminalsHIR.md) | `HIR/BuildReactiveScopeTerminalsHIR.ts` | Insert scope terminals into CFG |
| 18 | [flattenReactiveLoopsHIR](18-flattenReactiveLoopsHIR.md) | `ReactiveScopes/FlattenReactiveLoopsHIR.ts` | Prune scopes inside loops |
### Scope Flattening & Dependencies (19-20)
| # | Pass | File | Description |
|---|------|------|-------------|
| 19 | [flattenScopesWithHooksOrUseHIR](19-flattenScopesWithHooksOrUseHIR.md) | `ReactiveScopes/FlattenScopesWithHooksOrUseHIR.ts` | Prune scopes containing hooks |
| 20 | [propagateScopeDependenciesHIR](20-propagateScopeDependenciesHIR.md) | `HIR/PropagateScopeDependenciesHIR.ts` | Derive minimal scope dependencies |
### HIR → Reactive Conversion (21)
| # | Pass | File | Description |
|---|------|------|-------------|
| 21 | [buildReactiveFunction](21-buildReactiveFunction.md) | `ReactiveScopes/BuildReactiveFunction.ts` | Convert CFG to tree structure |
### Reactive Function Pruning (22-25)
| # | Pass | File | Description |
|---|------|------|-------------|
| 22 | [pruneUnusedLabels](22-pruneUnusedLabels.md) | `ReactiveScopes/PruneUnusedLabels.ts` | Remove unused labels |
| 23 | [pruneNonEscapingScopes](23-pruneNonEscapingScopes.md) | `ReactiveScopes/PruneNonEscapingScopes.ts` | Remove non-escaping scopes |
| | en | en | en_0000_README | 5 | |
24 | [pruneNonReactiveDependencies](24-pruneNonReactiveDependencies.md) | `ReactiveScopes/PruneNonReactiveDependencies.ts` | Remove non-reactive dependencies |
| 25 | [pruneUnusedScopes](25-pruneUnusedScopes.md) | `ReactiveScopes/PruneUnusedScopes.ts` | Remove empty scopes |
### Scope Optimization (26-28)
| # | Pass | File | Description |
|---|------|------|-------------|
| 26 | [mergeReactiveScopesThatInvalidateTogether](26-mergeReactiveScopesThatInvalidateTogether.md) | `ReactiveScopes/MergeReactiveScopesThatInvalidateTogether.ts` | Merge co-invalidating scopes |
| 27 | [pruneAlwaysInvalidatingScopes](27-pruneAlwaysInvalidatingScopes.md) | `ReactiveScopes/PruneAlwaysInvalidatingScopes.ts` | Prune always-invalidating scopes |
| 28 | [propagateEarlyReturns](28-propagateEarlyReturns.md) | `ReactiveScopes/PropagateEarlyReturns.ts` | Handle early returns in scopes |
### Codegen Preparation (29-31)
| # | Pass | File | Description |
|---|------|------|-------------|
| 29 | [promoteUsedTemporaries](29-promoteUsedTemporaries.md) | `ReactiveScopes/PromoteUsedTemporaries.ts` | Promote temps to named vars |
| 30 | [renameVariables](30-renameVariables.md) | `ReactiveScopes/RenameVariables.ts` | Ensure unique variable names |
| 31 | [codegenReactiveFunction](31-codegenReactiveFunction.md) | `ReactiveScopes/CodegenReactiveFunction.ts` | Generate final Babel AST |
### Transformations (32-38)
| # | Pass | File | Description |
|---|------|------|-------------|
| 34 | [optimizePropsMethodCalls](34-optimizePropsMethodCalls.md) | `Optimization/OptimizePropsMethodCalls.ts` | Normalize props method calls |
| 35 | [optimizeForSSR](35-optimizeForSSR.md) | `Optimization/OptimizeForSSR.ts` | SSR-specific optimizations |
| 36 | [outlineJSX](36-outlineJSX.md) | `Optimization/OutlineJsx.ts` | Outline JSX to components |
| 37 | [outlineFunctions](37-outlineFunctions.md) | `Optimization/OutlineFunctions.ts` | Outline pure functions |
| 38 | [memoizeFbtAndMacroOperandsInSameScope](38-memoizeFbtAndMacroOperandsInSameScope.md) | `ReactiveScopes/MemoizeFbtAndMacroOperandsInSameScope.ts` | Keep FBT operands together |
| en | en | en_0000_README | 6 | |
### Validation (39-55)
| # | Pass | File | Description |
|---|------|------|-------------|
| 39 | [validateContextVariableLValues](39-validateContextVariableLValues.md) | `Validation/ValidateContextVariableLValues.ts` | Variable reference consistency |
| 40 | [validateUseMemo](40-validateUseMemo.md) | `Validation/ValidateUseMemo.ts` | useMemo callback requirements |
| 41 | [validateHooksUsage](41-validateHooksUsage.md) | `Validation/ValidateHooksUsage.ts` | Rules of Hooks |
| 42 | [validateNoCapitalizedCalls](42-validateNoCapitalizedCalls.md) | `Validation/ValidateNoCapitalizedCalls.ts` | Component vs function calls |
| 43 | [validateLocalsNotReassignedAfterRender](43-validateLocalsNotReassignedAfterRender.md) | `Validation/ValidateLocalsNotReassignedAfterRender.ts` | Variable mutation safety |
| 44 | [validateNoSetStateInRender](44-validateNoSetStateInRender.md) | `Validation/ValidateNoSetStateInRender.ts` | No setState during render |
| 45 | [validateNoDerivedComputationsInEffects](45-validateNoDerivedComputationsInEffects.md) | `Validation/ValidateNoDerivedComputationsInEffects.ts` | Effect optimization hints |
| 46 | [validateNoSetStateInEffects](46-validateNoSetStateInEffects.md) | `Validation/ValidateNoSetStateInEffects.ts` | Effect performance |
| 47 | [validateNoJSXInTryStatement](47-validateNoJSXInTryStatement.md) | `Validation/ValidateNoJSXInTryStatement.ts` | Error boundary usage |
| 48 | [validateNoImpureValuesInRender](48-validateNoImpureValuesInRender.md) | `Validation/ValidateNoImpureValuesInRender.ts` | Impure value isolation |
| 49 | [validateNoRefAccessInRender](49-validateNoRefAccessInRender.md) | `Validation/ValidateNoRefAccessInRender.ts` | Ref access constraints |
| 50 | [validateNoFreezingKnownMutableFunctions](50-validateNoFreezingKnownMutableFunctions.md) | `Validation/ValidateNoFreezingKnownMutableFunctions.ts` | Mutable function isolation |
| | en | en | en_0000_README | 7 | |
51 | [validateExhaustiveDependencies](51-validateExhaustiveDependencies.md) | `Validation/ValidateExhaustiveDependencies.ts` | Dependency array completeness |
| 53 | [validatePreservedManualMemoization](53-validatePreservedManualMemoization.md) | `Validation/ValidatePreservedManualMemoization.ts` | Manual memo preservation |
| 54 | [validateStaticComponents](54-validateStaticComponents.md) | `Validation/ValidateStaticComponents.ts` | Component identity stability |
| 55 | [validateSourceLocations](55-validateSourceLocations.md) | `Validation/ValidateSourceLocations.ts` | Source location preservation |
## Key Data Structures
### HIR (High-level Intermediate Representation)
The compiler converts source code to HIR for analysis. Key types:
- **HIRFunction**: A function being compiled
- `body.blocks`: Map of BasicBlocks (control flow graph)
- `context`: Captured variables from outer scope
- `params`: Function parameters
- `returns`: The function's return place
- **BasicBlock**: A sequence of instructions with a terminal
- `instructions`: Array of Instructions
- `terminal`: Control flow (return, branch, etc.)
- `phis`: Phi nodes for SSA
- **Instruction**: A single operation
- `lvalue`: The place being assigned to
- `value`: The instruction kind (CallExpression, FunctionExpression, etc.)
- `effects`: Array of AliasingEffects
- **Place**: A reference to a value
- `identifier.id`: Unique IdentifierId
- `effect`: How the place is used (read, mutate, etc.)
### ReactiveFunction
After HIR is analyzed, it's converted to ReactiveFunction:
- Tree structure instead of CFG
- Contains ReactiveScopes that define memoization boundaries
- Each scope has dependencies and declarations
### AliasingEffects
Effects describe data flow and operations:
- **Capture/Alias**: Value relationships
- **Mutate/MutateTransitive**: Mutation tracking
- **Freeze**: Immutability marking
- **Render**: JSX usage context
- **Create/CreateFunction**: Value creation
## Feature Flags
Many passes are controlled by feature flags in `Environment.ts`:
| en | en | en_0000_README | 8 | |
| Flag | Enables Pass |
|------|--------------|
| `enableJsxOutlining` | outlineJSX |
| `enableFunctionOutlining` | outlineFunctions |
| `validateNoSetStateInRender` | validateNoSetStateInRender |
| `enableUseMemoCacheInterop` | Preserves manual memoization |
## Running Tests
```bash
# Run all tests
yarn snap
# Run specific fixture
yarn snap -p <fixture-name>
# Run with debug output (shows all passes)
yarn snap -p <fixture-name> -d
# Compile any file (not just fixtures) and see output
yarn snap compile <path>
# Compile any file with debug output (alternative to yarn snap -d -p when you don't have a fixture)
yarn snap compile --debug <path>
# Minimize a failing test case to its minimal reproduction
yarn snap minimize <path>
# Update expected outputs
yarn snap -u
```
## Fault Tolerance
The pipeline is fault-tolerant: all passes run to completion, accumulating errors on `Environment` rather than aborting on the first error.
- **Validation passes** are wrapped in `env.tryRecord()` in Pipeline.ts, which catches non-invariant `CompilerError`s and records them. If a validation pass throws, compilation continues.
- **Infrastructure/transformation passes** (enterSSA, eliminateRedundantPhi, inferMutationAliasingEffects, codegen, etc.) are NOT wrapped in `tryRecord()` because subsequent passes depend on their output being structurally valid. If they fail, compilation aborts.
- **`lower()` (BuildHIR)** always produces an `HIRFunction`, recording errors on `env` instead of returning `Err`. Unsupported constructs (e.g., `var`) are lowered best-effort.
- At the end of the pipeline, `env.hasErrors()` determines whether to return `Ok(codegen)` or `Err(aggregatedErrors)`.
## Further Reading
- [MUTABILITY_ALIASING_MODEL.md](../../src/Inference/MUTABILITY_ALIASING_MODEL.md): Detailed aliasing model docs
- [Pipeline.ts](../../src/Entrypoint/Pipeline.ts): Pass ordering and orchestration
- [HIR.ts](../../src/HIR/HIR.ts): Core data structure definitions
| en | en | en_0000_README | 9 | |
# [React](https://react.dev/) · [](https://github.com/facebook/react/blob/main/LICENSE) [](https://www.npmjs.com/package/react) [](https://github.com/facebook/react/actions/workflows/runtime_build_and_test.yml) [](https://github.com/facebook/react/actions/workflows/compiler_typescript.yml) [](https://legacy.reactjs.org/docs/how-to-contribute.html#your-first-pull-request)
React is a JavaScript library for building user interfaces.
* **Declarative:** React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable, simpler to understand, and easier to debug.
* **Component-Based:** Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep the state out of the DOM.
* **Learn Once, Write Anywhere:** We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using [Node](https://nodejs.org/en) and power mobile apps using [React Native](https://reactnative.dev/).
[Learn how to use React in your project](https://react.dev/learn).
| en | en | en_0001_README | 0 | |
## Installation
React has been designed for gradual adoption from the start, and **you can use as little or as much React as you need**:
* Use [Quick Start](https://react.dev/learn) to get a taste of React.
* [Add React to an Existing Project](https://react.dev/learn/add-react-to-an-existing-project) to use as little or as much React as you need.
* [Create a New React App](https://react.dev/learn/start-a-new-react-project) if you're looking for a powerful JavaScript toolchain.
## Documentation
You can find the React documentation [on the website](https://react.dev/).
Check out the [Getting Started](https://react.dev/learn) page for a quick overview.
The documentation is divided into several sections:
* [Quick Start](https://react.dev/learn)
* [Tutorial](https://react.dev/learn/tutorial-tic-tac-toe)
* [Thinking in React](https://react.dev/learn/thinking-in-react)
* [Installation](https://react.dev/learn/installation)
* [Describing the UI](https://react.dev/learn/describing-the-ui)
* [Adding Interactivity](https://react.dev/learn/adding-interactivity)
* [Managing State](https://react.dev/learn/managing-state)
* [Advanced Guides](https://react.dev/learn/escape-hatches)
* [API Reference](https://react.dev/reference/react)
* [Where to Get Support](https://react.dev/community)
* [Contributing Guide](https://legacy.reactjs.org/docs/how-to-contribute.html)
You can improve it by sending pull requests to [this repository](https://github.com/reactjs/react.dev).
## Examples
We have several examples [on the website](https://react.dev/). Here is the first one to get you started:
```jsx
import { createRoot } from 'react-dom/client';
function HelloMessage({ name }) {
return <div>Hello {name}</div>;
}
| en | en | en_0001_README | 1 | |
const root = createRoot(document.getElementById('container'));
root.render(<HelloMessage name="Taylor" />);
```
This example will render "Hello Taylor" into a container on the page.
You'll notice that we used an HTML-like syntax; [we call it JSX](https://react.dev/learn#writing-markup-with-jsx). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML.
## Contributing
The main purpose of this repository is to continue evolving React core, making it faster and easier to use. Development of React happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving React.
### [Code of Conduct](https://code.fb.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
### [Contributing Guide](https://legacy.reactjs.org/docs/how-to-contribute.html)
Read our [contributing guide](https://legacy.reactjs.org/docs/how-to-contribute.html) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to React.
### [Good First Issues](https://github.com/facebook/react/labels/good%20first%20issue)
To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first issues](https://github.com/facebook/react/labels/good%20first%20issue) that contain bugs that have a relatively limited scope. This is a great place to get started.
### License
React is [MIT licensed](./LICENSE).
| en | en | en_0001_README | 2 | |
# React Compiler
React Compiler is a compiler that optimizes React applications, ensuring that only the minimal parts of components and hooks will re-render when state changes. The compiler also validates that components and hooks follow the Rules of React.
More information about the design and architecture of the compiler are covered in the [Design Goals](./docs/DESIGN_GOALS.md).
More information about developing the compiler itself is covered in the [Development Guide](./docs/DEVELOPMENT_GUIDE.md). | en | en | en_0002_README | 0 | |
# pruneNonEscapingScopes
## File
`src/ReactiveScopes/PruneNonEscapingScopes.ts`
## Purpose
This pass prunes (removes) reactive scopes whose outputs do not "escape" the component and therefore do not need to be memoized. A value "escapes" in two ways:
1. **Returned from the function** - The value is directly returned or transitively aliased by a return value
2. **Passed to a hook** - Any value passed as an argument to a hook may be stored by React internally (e.g., the closure passed to `useEffect`)
The key insight is that values which never escape the component boundary can be safely recreated on each render without affecting the behavior of consumers.
## Input Invariants
- The input is a `ReactiveFunction` after scope blocks have been identified
- Reactive scopes have been assigned to instructions
- The pass runs after `BuildReactiveFunction` and `PruneUnusedLabels`, before `PruneNonReactiveDependencies`
| en | en | en_0003_23-pruneNonEscapingScopes | 0 | |
## Output Guarantees
- **Scopes with non-escaping outputs are removed** - Their instructions are inlined back into the parent scope/function body
- **Scopes with escaping outputs are retained** - Values that escape via return or hook arguments remain memoized
- **Transitive dependencies of escaping scopes are preserved** - If an escaping scope depends on a non-escaping value, that value's scope is also retained to prevent unnecessary invalidation
- **`FinishMemoize` instructions are marked `pruned=true`** - When a scope is pruned, the associated memoization instructions are flagged
## Algorithm
### Phase 1: Build the Dependency Graph
Using `CollectDependenciesVisitor`, build:
- **Identifier nodes** - Each node tracks memoization level, dependencies, scopes, and whether ultimately memoized
- **Scope nodes** - Each scope tracks its dependencies
- **Escaping values** - Identifiers that escape via return or hook arguments
| en | en | en_0003_23-pruneNonEscapingScopes | 1 | |
### Phase 2: Classify Memoization Levels
Each instruction value is classified:
- `Memoized`: Arrays, objects, function calls, `new` expressions - always potentially aliasing
- `Conditional`: Conditional/logical expressions, property loads - memoized only if dependencies are memoized
- `Unmemoized`: JSX elements (when `memoizeJsxElements` is false), DeclareLocal
- `Never`: Primitives, LoadGlobal, binary/unary expressions - can be cheaply compared
### Phase 3: Compute Memoized Identifiers
`computeMemoizedIdentifiers()` performs a graph traversal starting from escaping values:
- For each escaping value, recursively visit its dependencies
- Mark values and their scopes based on memoization level
- When marking a scope, force-memoize all its dependencies
### Phase 4: Prune Scopes
`PruneScopesTransform` visits each scope block:
- If any scope output is in the memoized set, keep the scope
- If no outputs are memoized, replace the scope block with its inlined instructions
## Edge Cases
| en | en | en_0003_23-pruneNonEscapingScopes | 2 | |
### Interleaved Mutations
```javascript
const a = [props.a]; // independently memoizable, non-escaping
const b = [];
const c = {};
c.a = a; // c captures a, but c doesn't escape
b.push(props.b); // b escapes via return
return b;
```
Here `a` does not directly escape, but it is a dependency of the scope containing `b`. The algorithm correctly identifies that `a`'s scope must be preserved.
### Hook Arguments Escape
Values passed to hooks are treated as escaping because hooks may store references internally.
### JSX Special Handling
JSX elements are marked as `Unmemoized` by default because React.memo() can handle dynamic memoization.
### noAlias Functions
If a function signature indicates `noAlias === true`, its arguments are not treated as escaping.
### Reassignments
When a scope reassigns a variable, the scope is added as a dependency of that variable.
## TODOs
None explicitly in the source file.
## Example
### Fixture: `escape-analysis-non-escaping-interleaved-allocating-dependency.js`
| en | en | en_0003_23-pruneNonEscapingScopes | 3 | |
**Input:**
```javascript
function Component(props) {
const a = [props.a];
const b = [];
const c = {};
c.a = a;
b.push(props.b);
return b;
}
```
**Output:**
```javascript
function Component(props) {
const $ = _c(5);
let t0;
if ($[0] !== props.a) {
t0 = [props.a];
$[0] = props.a;
$[1] = t0;
} else {
t0 = $[1];
}
const a = t0; // a is memoized even though it doesn't escape directly
let b;
if ($[2] !== a || $[3] !== props.b) {
b = [];
const c = {}; // c is NOT memoized - it doesn't escape
c.a = a;
b.push(props.b);
$[2] = a;
$[3] = props.b;
$[4] = b;
} else {
b = $[4];
}
return b;
}
```
Key observations:
- `a` is memoized because it's a dependency of the scope containing `b`
- `c` is not separately memoized because it doesn't escape
- `b` is memoized because it's returned
| en | en | en_0003_23-pruneNonEscapingScopes | 4 | |
# validateNoCapitalizedCalls
## File
`src/Validation/ValidateNoCapitalizedCalls.ts`
## Purpose
This validation pass ensures that capitalized functions are not called directly in a component. In React, capitalized functions are conventionally reserved for components, which should be invoked via JSX syntax rather than direct function calls.
Direct calls to capitalized functions can cause issues because:
1. Components may contain hooks, and calling them directly violates the Rules of Hooks
2. The React runtime expects components to be rendered via JSX for proper reconciliation
3. Direct calls bypass React's rendering lifecycle and state management
This validation is opt-in and controlled by the `validateNoCapitalizedCalls` configuration option.
## Input Invariants
- The function has been lowered to HIR
- Global bindings have been resolved
- The `validateNoCapitalizedCalls` configuration option is enabled (via pragma or config)
## Validation Rules
### Rule 1: No Direct Calls to Capitalized Globals
Capitalized global functions (not in the allowlist) cannot be called directly.
**Error:**
```
Error: Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config
[FunctionName] may be a component.
```
| en | en | en_0004_42-validateNoCapitalizedCalls | 0 | |
### Rule 2: No Direct Method Calls to Capitalized Properties
Capitalized methods on objects cannot be called directly.
**Error:**
```
Error: Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config
[MethodName] may be a component.
```
## Algorithm
### Phase 1: Build Allowlist
```typescript
const ALLOW_LIST = new Set([
...DEFAULT_GLOBALS.keys(), // Built-in globals (Array, Object, etc.)
...(envConfig.validateNoCapitalizedCalls ?? []), // User-configured allowlist
]);
const isAllowed = (name: string): boolean => {
return ALLOW_LIST.has(name);
};
```
### Phase 2: Track Capitalized Globals and Properties
```typescript
const capitalLoadGlobals = new Map<IdentifierId, string>();
const capitalizedProperties = new Map<IdentifierId, string>();
```
### Phase 3: Scan Instructions
```typescript
for (const instr of block.instructions) {
switch (value.kind) {
case 'LoadGlobal':
// Track capitalized globals (excluding CONSTANTS)
if (
value.binding.name !== '' &&
/^[A-Z]/.test(value.binding.name) &&
!(value.binding.name.toUpperCase() === value.binding.name) &&
!isAllowed(value.binding.name)
) {
| en | en | en_0004_42-validateNoCapitalizedCalls | 1 | |
capitalLoadGlobals.set(lvalue.identifier.id, value.binding.name);
}
break;
case 'CallExpression':
// Check if calling a tracked capitalized global
const calleeName = capitalLoadGlobals.get(value.callee.identifier.id);
if (calleeName != null) {
CompilerError.throwInvalidReact({
reason: 'Capitalized functions are reserved for components...',
description: `${calleeName} may be a component`,
...
});
}
break;
case 'PropertyLoad':
// Track capitalized properties
if (typeof value.property === 'string' && /^[A-Z]/.test(value.property)) {
capitalizedProperties.set(lvalue.identifier.id, value.property);
}
break;
case 'MethodCall':
// Check if calling a tracked capitalized property
const propertyName = capitalizedProperties.get(value.property.identifier.id);
if (propertyName != null) {
errors.push({
reason: 'Capitalized functions are reserved for components...',
description: `${propertyName} may be a component`,
...
});
}
break;
}
}
```
## Edge Cases
| en | en | en_0004_42-validateNoCapitalizedCalls | 2 | |
### ALL_CAPS Constants
Functions with names that are entirely uppercase (like `CONSTANTS`) are not flagged:
```javascript
const x = MY_CONSTANT(); // Not an error - all caps indicates a constant, not a component
const y = MyComponent(); // Error - PascalCase indicates a component
```
### Built-in Globals
The default globals from `DEFAULT_GLOBALS` are automatically allowlisted:
```javascript
const arr = Array(5); // OK - Array is a built-in
const obj = Object.create(null); // OK - Object is a built-in
```
### User-Configured Allowlist
Users can allowlist specific functions via configuration:
```typescript
validateNoCapitalizedCalls: ['MyUtility', 'SomeFactory']
```
### Method Calls vs Function Calls
Both direct function calls and method calls on objects are checked:
```javascript
MyComponent(); // Error - direct call
someObject.MyComponent(); // Error - method call
```
### Chained Property Access
Only the immediate property being called is checked:
```javascript
a.b.MyComponent(); // Only checks if MyComponent is capitalized
```
## TODOs
None in the source file.
## Example
### Fixture: `error.capitalized-function-call.js`
**Input:**
```javascript
// @validateNoCapitalizedCalls
function Component() {
const x = SomeFunc();
return x;
}
```
**Error:**
```
Error: Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config
SomeFunc may be a component.
| en | en | en_0004_42-validateNoCapitalizedCalls | 3 | |
error.capitalized-function-call.ts:3:12
1 | // @validateNoCapitalizedCalls
2 | function Component() {
> 3 | const x = SomeFunc();
| ^^^^^^^^^^ Capitalized functions are reserved for components...
4 |
5 | return x;
6 | }
```
### Fixture: `error.capitalized-method-call.js`
**Input:**
```javascript
// @validateNoCapitalizedCalls
function Component() {
const x = someGlobal.SomeFunc();
return x;
}
```
**Error:**
```
Error: Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config
SomeFunc may be a component.
error.capitalized-method-call.ts:3:12
1 | // @validateNoCapitalizedCalls
2 | function Component() {
> 3 | const x = someGlobal.SomeFunc();
| ^^^^^^^^^^^^^^^^^^^^^ Capitalized functions are reserved for components...
4 |
5 | return x;
6 | }
```
### Fixture: `capitalized-function-allowlist.js` (No Error)
**Input:**
```javascript
// @validateNoCapitalizedCalls:["SomeFunc"]
function Component() {
const x = SomeFunc();
return x;
}
```
**Output:**
Compiles successfully because `SomeFunc` is in the allowlist.
| en | en | en_0004_42-validateNoCapitalizedCalls | 4 | |
# Attribute Behavior Fixture
**WIP:** This is an MVP, still needs polish.
### Known Issues
- There are currently two errors thrown when the page loads;
`SyntaxError: missing ; before statement`
## Instructions
`yarn build --type=UMD_DEV react/index,react-dom && cd fixtures/attribute-behavior && yarn install && yarn dev`
## Interpretation
Each row is an attribute which could be set on some DOM component. Some of
them are invalid or mis-capitalized or mixed up versions of real ones.
Each column is a value which can be passed to that attribute.
Every cell has a box on the left and a box on the right.
The left box shows the property (or attribute) assigned by the latest stable release of React, and the
right box shows the property (or attribute) assigned by the locally built version of React.
Right now, we use a purple outline to call out cases where the assigned property
(or attribute) has changed between React 15 and 16.
---
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
You can find the guide for how to do things in a CRA [here](https://github.com/facebook/create-react-app/blob/main/packages/cra-template/template/README.md).
| en | en | en_0005_README | 0 | |
# DOM Fixtures
A set of DOM test cases for quickly identifying browser issues.
## Setup
To reference a local build of React, first run `yarn build` at the root
of the React project. Then:
```
cd fixtures/dom
yarn
yarn dev
```
The `dev` command runs a script that copies over the local build of react into
the public directory.
| en | en | en_0006_README | 0 | |
# ESLint v10 Fixture
This fixture allows us to test e2e functionality for `eslint-plugin-react-hooks` with eslint version 10.
Run the following to test.
```sh
cd fixtures/eslint-v10
yarn
yarn build
yarn lint
```
| en | en | en_0007_README | 0 | |
# ESLint v6 Fixture
This fixture allows us to test e2e functionality for `eslint-plugin-react-hooks` with eslint version 6.
Run the following to test.
```sh
cd fixtures/eslint-v6
yarn
yarn build
yarn lint
```
| en | en | en_0008_README | 0 | |
# ESLint v7 Fixture
This fixture allows us to test e2e functionality for `eslint-plugin-react-hooks` with eslint version 7.
Run the following to test.
```sh
cd fixtures/eslint-v7
yarn
yarn build
yarn lint
```
| en | en | en_0009_README | 0 | |
# ESLint v8 Fixture
This fixture allows us to test e2e functionality for `eslint-plugin-react-hooks` with eslint version 8.
Run the following to test.
```sh
cd fixtures/eslint-v8
yarn
yarn build
yarn lint
```
| en | en | en_0010_README | 0 | |
# ESLint v9 Fixture
This fixture allows us to test e2e functionality for `eslint-plugin-react-hooks` with eslint version 9.
Run the following to test.
```sh
cd fixtures/eslint-v9
yarn
yarn build
yarn lint
```
| en | en | en_0011_README | 0 | |
# Fiber Debugger
This is a debugger handy for visualizing how [Fiber](https://github.com/facebook/react/issues/6170) works internally.
**It is only meant to be used by React contributors, and not by React users.**
It is likely that it might get broken at some point. If it's broken, ping [Dan](https://twitter.com/dan_abramov).
### Running
First, `npm run build` in React root repo folder.
Then `npm install` and `npm start` in this folder.
Open `http://localhost:3000` in Chrome.
### Features
* Edit code that uses `ReactNoop` renderer
* Visualize how relationships between fibers change over time
* Current tree is displayed in green

| en | en | en_0012_README | 0 | |
# Fizz Fixtures
A set of basic tests for Fizz primarily focused on baseline performance of legacy renderToString and streaming implementations.
## Setup
To reference a local build of React, first run `npm run build` at the root
of the React project. Then:
```
cd fixtures/fizz
yarn
yarn start
```
The `start` command runs a webpack dev server and a server-side rendering server in development mode with hot reloading.
**Note: whenever you make changes to React and rebuild it, you need to re-run `yarn` in this folder:**
```
yarn
```
If you want to try the production mode instead run:
```
yarn start:prod
```
This will pre-build all static resources and then start a server-side rendering HTTP server that hosts the React app and service the static resources (without hot reloading).
| en | en | en_0013_README | 0 | |
# Legacy JSX Runtimes
This is an internal testing fixture for the special JSX runtime versions released for 0.14, 15, and 16.
They are checked into the corresponding `react-*/cjs/*` folders.
Run the full regression suite:
```
yarn
yarn test
```
| en | en | en_0014_README | 0 | |
# Nested React Demo
This is a demo of how you can configure a build system to serve **two different versions of React** side by side in the same app. This is not optimal, and should only be used as a compromise to prevent your app from getting stuck on an old version of React.
## You Probably Don't Need This
Note that **this approach is meant to be an escape hatch, not the norm**.
Normally, we encourage you to use a single version of React across your whole app. When you need to upgrade React, it is better to try to upgrade it all at once. We try to keep breaking changes between versions to the minimum, and often there are automatic scripts ("codemods") that can assist you with migration. You can always find the migration information for any release on [our blog](https://reactjs.org/blog/).
Using a single version of React removes a lot of complexity. It is also essential to ensure the best experience for your users who don't have to download the code twice. Always prefer using one React.
## What Is This For?
However, for some apps that have been in production for many years, upgrading all screens at once may be prohibitively difficult. For example, React components written in 2014 may still rely on [the unofficial legacy context API](https://reactjs.org/docs/legacy-context.html) (not to be confused with the modern one), and are not always maintained.
Traditionally, this meant that if a legacy API is deprecated, you would be stuck on the old version of React forever. That prevents your whole app from receiving improvements and bugfixes. This repository demonstrates a hybrid approach. It shows how you can use a newer version of React for some parts of your app, while **lazy-loading an older version of React** for the parts that haven't been migrated yet.
This approach is inherently more complex, and should be used as a last resort when you can't upgrade.
## Version Requirements
| en | en | en_0015_README | 0 | |
This demo uses two different versions of React: React 17 for "modern" components (in `src/modern`), and React 16.8 for "legacy" components (in `src/legacy`).
**We still recommend upgrading your whole app to React 17 in one piece.** The React 17 release intentionally has minimal breaking changes so that it's easier to upgrade to. In particular, React 17 solves some problems with nesting related to event propagation that earlier versions of React did not handle well. We expect that this nesting demo may not be as useful today as during a future migration from React 17 to the future major versions where some of the long-deprecated APIs may be removed.
However, if you're already stuck on an old version of React, you may found this approach useful today. If you remove a Hook call from `src/shared/Clock.js`, you can downgrade the legacy React all the way down to React 16.3. If you then remove Context API usage from `src/legacy/createLegacyRoot.js`, you can further downgrade the legacy React version, but keep in mind that the usage of third-party libraries included in this demo (React Router and React Redux) may need to be adjusted or removed.
## Installation
To run this demo, open its folder in Terminal and execute:
```sh
npm install
npm start
```
If you want to test the production build, you can run instead:
```
npm install
npm run build
npx serve -s build
```
This sample app uses client-side routing and consists of two routes:
- `/` renders a page which uses a newer version of React. (In the production build, you can verify that only one version of React is being loaded when this route is rendered.)
- `/about` renders a page which uses an older version of React for a part of its tree. (In the production build, you can verify that both versions of React are loaded from different chunks.)
**The purpose of this demo is to show some nuances of such setup:**
| en | en | en_0015_README | 1 | |
- How to install two versions of React in a single app with npm side by side.
- How to avoid the ["invalid Hook call" error](https://github.com/facebook/react/issues/13991) while nesting React trees.
- How to pass context between different versions of React.
- How to lazy-load the second React bundle so it's only loaded on the screens that use it.
- How to do all of this without a special bundler configuration.
## How It Works
File structure is extremely important in this demo. It has a direct effect on which code is going to use which version of React. This particular demo is using Create React App without ejecting, so **it doesn't rely on any bundler plugins or configuration**. The principle of this demo is portable to other setups.
### Dependencies
We will use three different `package.json`s: one for non-React code at the root, and two in the respective `src/legacy` and `src/modern` folders that specify the React dependencies:
- **`package.json`**: The root `package.json` is a place for build dependencies (such as `react-scripts`) and any React-agnostic libraries (for example, `lodash`, `immer`, or `redux`). We do **not** include React or any React-related libraries in this file.
- **`src/legacy/package.json`**: This is where we declare the `react` and `react-dom` dependencies for the "legacy" trees. In this demo, we're using React 16.8 (although, as noted above, we could downgrade it further below). This is **also** where we specify any third-party libraries that use React. For example, we include `react-router` and `react-redux` in this example.
- | en | en | en_0015_README | 2 | |
**`src/modern/package.json`**: This is where we declare the `react` and `react-dom` dependencies for the "modern" trees. In this demo, we're using React 17. Here, we also specify third-party dependencies that use React and are used from the modern part of our app. This is why we *also* have `react-router` and `react-redux` in this file. (Their versions don't strictly have to match their `legacy` counterparts, but features that rely on context may require workarounds if they differ.)
The `scripts` in the root `package.json` are set up so that when you run `npm install` in it, it also runs `npm install` in both `src/legacy` and `src/modern` folders.
**Note:** This demo is set up to use a few third-party dependencies (React Router and Redux). These are not essential, and you can remove them from the demo. They are included so we can show how to make them work with this approach.
### Folders
There are a few key folders in this example:
- **`src`**: Root of the source tree. At this level (or below it, except for the special folders noted below), you can put any logic that's agnostic of React. For example, in this demo we have `src/index.js` which is the app's entry point, and `src/store.js` which exports a Redux store. These regular modules only execute once, and are **not** duplicated between the bundles.
- **`src/legacy`**: This is where all the code using the older version of React should go. This includes React components and Hooks, and general product code that is **only** used by the legacy trees.
- **`src/modern`**: This is where all the code using the newer version of React should go. This includes React components and Hooks, and general product code that is **only** used by the modern trees.
- **`src/shared`**: You may have some components or Hooks that you wish to use from both modern and legacy subtrees. The build process is set up so that **everything inside `src/shared` gets copied by a file watcher** into both `src/legacy/shared` and `src/modern/shared` on every change. This lets you write a component or a Hook once, but reuse it in both places.
### Lazy Loading
| en | en | en_0015_README | 3 | |
Loading two Reacts on the same page is bad for the user experience, so you should strive to push this as far as possible from the critical path of your app. For example, if there is a dialog that is less commonly used, or a route that is rarely visited, those are better candidates for staying on an older version of React than parts of your homepage.
To encourage only loading the older React when necessary, this demo includes a helper that works similarly to `React.lazy`. For example, `src/modern/AboutPage.js`, simplified, looks like this:
```js
import lazyLegacyRoot from './lazyLegacyRoot';
// Lazy-load a component from the bundle using legacy React.
const Greeting = lazyLegacyRoot(() => import('../legacy/Greeting'));
function AboutPage() {
return (
<>
<h3>This component is rendered by React ({React.version}).</h3>
<Greeting />
</>
);
}
```
As a result, only if the `AboutPage` (and as a result, `<Greeting />`) gets rendered, we will load the bundle containing the legacy React and the legacy `Greeting` component. Like with `React.lazy()`, we wrap it in `<Suspense>` to specify the loading indicator:
```js
<Suspense fallback={<Spinner />}>
<AboutPage />
</Suspense>
```
If the legacy component is only rendered conditionally, we won't load the second React until it's shown:
```js
<>
<button onClick={() => setShowGreeting(true)}>
Say hi
</button>
{showGreeting && (
<Suspense fallback={<Spinner />}>
<Greeting />
</Suspense>
)}
</>
```
The implementation of the `src/modern/lazyLegacyRoot.js` helper is included so you can tweak it and customize it to your needs. Remember to test lazy loading with the production builds because the bundler may not optimize it in development.
### Context
| en | en | en_0015_README | 4 | |
If you have nested trees managed by different versions of React, the inner tree won't "see" the outer tree's Context.
This breaks third-party libraries like React Redux or React Router, as well as any of your own usage of Context (for example, for theming).
To solve this problem, we read all the Contexts we care about in the outer tree, pass them to the inner tree, and then wrap the inner tree in the corresponding Providers. You can see this in action in two files:
* `src/modern/lazyLegacyRoot.js`: Look for `useContext` calls, and how their results are combined into a single object that is passed through. **You can read more Contexts there** if your app requires them.
* `src/legacy/createLegacyRoot.js`: Look for the `Bridge` component which receives that object and wraps its children with the appropriate Context Providers. **You can wrap them with more Providers there** if your app requires them.
Note that, generally saying, this approach is somewhat fragile, especially because some libraries may not expose their Contexts officially or consider their structure private. You may be able to expose private Contexts by using a tool like [patch-package](https://www.npmjs.com/package/patch-package), but remember to keep all the versions pinned because even a patch release of a third-party library may change the behavior.
### Nesting Direction
In this demo, we use an older React inside an app managed by the newer React. However, we could rename the folders and apply the same approach in the other direction.
### Event Propagation
Note that before React 17, `event.stopPropagation()` in the inner React tree does not prevent the event propagation to the outer React tree. This may cause unexpected behavior when extracting a UI tree like a dialog to use a separate React. This is because prior to React 17, both Reacts would attach the ev | en | en | en_0015_README | 5 | |
ent listener at the `document` level. React 17 fixes this by attaching handlers to the roots. We strongly recommend upgrading to React 17 before considering the nesting strategy for future upgrades.
### Gotchas
This setup is unusual, so it has a few gotchas.
* Don't add `package.json` to the `src/shared` folder. For example, if you want to use an npm React component inside `src/shared`, you should add it to both `src/modern/package.json` and `src/legacy/package.json` instead. You can use different versions of it but make sure your code works with both of them — and that it works with both Reacts!
* Don't use React outside of the `src/modern`, `src/legacy`, or `src/shared`. Don't add React-related libraries outside of `src/modern/package.json` or `src/legacy/package.json`.
* Remember that `src/shared` is where you write shared components, but the files you write there are automatically copied into `src/modern/shared` and `src/legacy/shared`, **from which you should import them**. Both of the target directories are in `.gitignore`. Importing directly from `src/shared` **will not work** because it is ambiguous what `react` refers to in that folder.
* Keep in mind that any code in `src/shared` gets duplicated between the legacy and the modern bundles. Code that should not be duplicated needs to be anywhere else in `src` (but you can't use React there since the version is ambiguous).
* You'll want to exclude `src/*/node_modules` from your linter's configuration, as this demo does in `.eslintignorerc`.
This setup is complicated, and we don't recommend it for most apps. However, we believe it is important to offer it as an option for apps that would otherwise get left behind. There might be ways to simplify it with a layer of tooling, but this example is intentionally showing the low-level mechanism that other tools may build on.
| en | en | en_0015_README | 6 | |
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
| en | en | en_0016_README | 0 | |
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
| en | en | en_0016_README | 1 | |
# Manual Testing Fixtures
This folder exists for **React contributors** only.
If you use React, you don't need to worry about it.
These fixtures verify that the built React distributions are usable in different environments.
**They are not running automatically.** (At least not yet. Feel free to contribute to automate them.)
Run them when you make changes to how we package React and ReactDOM.
## How to Run
First, build React and the fixtures:
```
cd react
npm run build
node fixtures/packaging/build-all.js
```
Then run a local server, e.g.
```
npx pushstate-server .
```
and open the following URL in your browser: [http://localhost:9000/fixtures/packaging/index.html](http://localhost:9000/fixtures/packaging/index.html)
You should see two things:
* A number of iframes (corresponding to various builds), with "Hello World" rendered in each iframe.
* No errors in the console.
| en | en | en_0017_README | 0 | |
# SSR Fixtures
A set of test cases for quickly identifying issues with server-side rendering.
## Setup
To reference a local build of React, first run `npm run build` at the root
of the React project. Then:
```
cd fixtures/ssr
yarn
yarn start
```
The `start` command runs a webpack dev server and a server-side rendering server in development mode with hot reloading.
**Note: whenever you make changes to React and rebuild it, you need to re-run `yarn` in this folder:**
```
yarn
```
If you want to try the production mode instead run:
```
yarn start:prod
```
This will pre-build all static resources and then start a server-side rendering HTTP server that hosts the React app and service the static resources (without hot reloading).
| en | en | en_0018_README | 0 | |
# SSR Fixtures
A set of test cases for quickly identifying issues with server-side rendering.
## Setup
To reference a local build of React, first run `npm run build` at the root
of the React project. Then:
```
cd fixtures/ssr2
yarn
yarn start
```
The `start` command runs a webpack dev server and a server-side rendering server in development mode with hot reloading.
**Note: whenever you make changes to React and rebuild it, you need to re-run `yarn` in this folder:**
```
yarn
```
If you want to try the production mode instead run:
```
yarn start:prod
```
This will pre-build all static resources and then start a server-side rendering HTTP server that hosts the React app and service the static resources (without hot reloading).
| en | en | en_0019_README | 0 | |
# View Transition
A test case for View Transitions.
## Setup
To reference a local build of React, first run `npm run build` at the root
of the React project. Then:
```
cd fixtures/view-transition
yarn
yarn start
```
The `start` command runs a webpack dev server and a server-side rendering server in development mode with hot reloading.
**Note: whenever you make changes to React and rebuild it, you need to re-run `yarn` in this folder:**
```
yarn
```
If you want to try the production mode instead run:
```
yarn start:prod
```
This will pre-build all static resources and then start a server-side rendering HTTP server that hosts the React app and service the static resources (without hot reloading).
| en | en | en_0020_README | 0 | |
# `dom-event-testing-library`
A library for unit testing events via high-level interactions, e.g., `pointerdown`,
that produce realistic and complete DOM event sequences.
There are number of challenges involved in unit testing modules that work with
DOM events.
1. Gesture recognizers may need to support environments with and without support for
the `PointerEvent` API.
2. Gesture recognizers may need to support various user interaction modes including
mouse, touch, and pen use.
3. Gesture recognizers must account for the actual event sequences browsers produce
(e.g., emulated touch and mouse events.)
4. Gesture recognizers must work with "virtual" events produced by tools like
screen-readers.
Writing unit tests to cover all these scenarios is tedious and error prone. This
event testing library is designed to solve these issues by allowing developers to
more easily dispatch events in unit tests, and to more reliably test pointer
interactions using a high-level API based on `PointerEvent`. Here's a basic example:
```js
import {
describeWithPointerEvent,
testWithPointerType,
createEventTarget,
setPointerEvent,
resetActivePointers
} from 'dom-event-testing-library';
describeWithPointerEvent('useTap', hasPointerEvent => {
beforeEach(() => {
// basic PointerEvent mock
setPointerEvent(hasPointerEvent);
});
afterEach(() => {
// clear active pointers between test runs
resetActivePointers();
});
| en | en | en_0021_README | 0 | |
// test all the pointer types supported by the environment
testWithPointerType('pointer down', pointerType => {
const ref = createRef(null);
const onTapStart = jest.fn();
render(() => {
useTap(ref, { onTapStart });
return <div ref={ref} />
});
// create an event target
const target = createEventTarget(ref.current);
// dispatch high-level pointer event
target.pointerdown({ pointerType });
expect(onTapStart).toBeCalled();
});
});
```
This tests the interaction in multiple scenarios. In each case, a realistic DOM
event sequence–with complete mock events–is produced. When running in a mock
environment without the `PointerEvent` API, the test runs for both `mouse` and
`touch` pointer types. When `touch` is the pointer type it produces emulated mouse
events. When running in a mock environment with the `PointerEvent` API, the test
runs for `mouse`, `touch`, and `pen` pointer types.
It's important to cover all these scenarios because it's very easy to introduce
bugs – e.g., double calling of callbacks – if not accounting for emulated mouse
events, differences in target capturing between `touch` and `mouse` pointers, and
the different semantics of `button` across event APIs.
Default values are provided for the expected native events properties. They can
also be customized as needed in a test.
```js
target.pointerdown({
button: 0,
buttons: 1,
pageX: 10,
pageY: 10,
pointerType,
// NOTE: use x,y instead of clientX,clientY
x: 10,
y: 10
});
```
Tests that dispatch multiple pointer events will dispatch multi-touch native events
on the target.
```js
// first pointer is active
target.pointerdown({pointerId: 1, pointerType});
// second pointer is active
target.pointerdown({pointerId: 2, pointerType});
```
| en | en | en_0021_README | 1 | |
# `eslint-plugin-react-hooks`
The official ESLint plugin for [React](https://react.dev) which enforces the [Rules of React](https://react.dev/reference/eslint-plugin-react-hooks) and other best practices.
## Installation
Assuming you already have ESLint installed, run:
```sh
# npm
npm install eslint-plugin-react-hooks --save-dev
# yarn
yarn add eslint-plugin-react-hooks --dev
```
### Flat Config (eslint.config.js|ts)
Add the `recommended` config for all recommended rules:
```js
// eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks';
import { defineConfig } from 'eslint/config';
export default defineConfig([
reactHooks.configs.flat.recommended,
]);
```
If you want to try bleeding edge experimental compiler rules, use `recommended-latest`.
```js
// eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks';
import { defineConfig } from 'eslint/config';
export default defineConfig([
reactHooks.configs.flat['recommended-latest'],
]);
```
### Legacy Config (.eslintrc)
If you are still using ESLint below 9.0.0, the `recommended` preset can also be used to enable all recommended rules.
| en | en | en_0022_README | 0 | |
```js
{
"extends": ["plugin:react-hooks/recommended"],
// ...
}
```
### Custom Configuration
If you want more fine-grained configuration, you can instead choose to enable specific rules. However, we strongly encourage using the recommended presets — see above — so that you will automatically receive new recommended rules as we add them in future versions of the plugin.
#### Flat Config (eslint.config.js|ts)
```js
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{
files: ['**/*.{js,jsx}'],
plugins: { 'react-hooks': reactHooks },
// ...
rules: {
// Core hooks rules
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
// React Compiler rules
'react-hooks/config': 'error',
'react-hooks/error-boundaries': 'error',
'react-hooks/component-hook-factories': 'error',
'react-hooks/gating': 'error',
'react-hooks/globals': 'error',
'react-hooks/immutability': 'error',
'react-hooks/preserve-manual-memoization': 'error',
'react-hooks/purity': 'error',
| en | en | en_0022_README | 1 | |
'react-hooks/refs': 'error',
'react-hooks/set-state-in-effect': 'error',
'react-hooks/set-state-in-render': 'error',
'react-hooks/static-components': 'error',
'react-hooks/unsupported-syntax': 'warn',
'react-hooks/use-memo': 'error',
'react-hooks/incompatible-library': 'warn',
}
},
];
```
#### Legacy Config (.eslintrc)
```js
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
// Core hooks rules
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
// React Compiler rules
"react-hooks/config": "error",
"react-hooks/error-boundaries": "error",
"react-hooks/component-hook-factories": "error",
"react-hooks/gating": "error",
"react-hooks/globals": "error",
"react-hooks/immutability": "error",
"react-hooks/preserve-manual-memoization": "error",
"react-hooks/purity": "error",
"react-hooks/refs": "error",
"react-hooks/set-state-in-effect": "error",
"react-hooks/set-state-in-render": "error",
| en | en | en_0022_README | 2 | |
"react-hooks/static-components": "error",
"react-hooks/unsupported-syntax": "warn",
"react-hooks/use-memo": "error",
"react-hooks/incompatible-library": "warn"
}
}
```
## Advanced Configuration
`exhaustive-deps` can be configured to validate dependencies of custom Hooks with the `additionalHooks` option.
This option accepts a regex to match the names of custom Hooks that have dependencies.
```js
{
rules: {
// ...
"react-hooks/exhaustive-deps": ["warn", {
additionalHooks: "(useMyCustomHook|useMyOtherCustomHook)"
}]
}
}
```
We suggest to use this option **very sparingly, if at all**. Generally saying, we recommend most custom Hooks to not use the dependencies argument, and instead provide a higher-level API that is more focused around a specific use case.
## Valid and Invalid Examples
Please refer to the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks) documentation to learn more about this rule.
## License
MIT
| en | en | en_0022_README | 3 | |
# React ART
React ART is a JavaScript library for drawing vector graphics using [React](https://github.com/facebook/react/).
It provides declarative and reactive bindings to the [ART library](https://github.com/sebmarkbage/art/).
Using the same declarative API you can render the output to either Canvas, SVG or VML (IE8).
| en | en | en_0023_README | 0 | |
# react-cache
A basic cache for React applications. It also serves as a reference for more
advanced caching implementations.
This package is meant to be used alongside yet-to-be-released, experimental
React features. It's unlikely to be useful in any other context.
**Do not use in a real application.** We're publishing this early for
demonstration purposes.
**Use it at your own risk.**
# No, Really, It Is Unstable
The API ~~may~~ will change wildly between versions.
| en | en | en_0024_README | 0 | |
# react-client
This is an experimental package for consuming custom React streaming models.
**Its API is not as stable as that of React, React Native, or React DOM, and does not follow the common versioning scheme.**
**Use it at your own risk.**
| en | en | en_0025_README | 0 | |
# react-debug-tools
This is an experimental package for debugging React renderers.
**Its API is not as stable as that of React, React Native, or React DOM, and does not follow the common versioning scheme.**
**Use it at your own risk.**
| en | en | en_0026_README | 0 | |
# `react-devtools-core`
This package provides low-level APIs to support renderers like [React Native](https://github.com/facebook/react-native). If you're looking for the standalone React DevTools UI, **we suggest using [`react-devtools`](https://github.com/facebook/react/tree/main/packages/react-devtools) instead of using this package directly**.
This package provides two entrypoints: labeled "backend" and "standalone" (frontend). Both APIs are described below.
# Backend API
Backend APIs are embedded in _development_ builds of renderers like [React Native](https://github.com/facebook/react-native) in order to connect to the React DevTools UI.
### Example
If you are building a non-browser-based React renderer, you can use the backend API like so:
```js
if (process.env.NODE_ENV !== 'production') {
const { initialize, connectToDevTools } = require("react-devtools-core");
initialize(settings);
// Must be called before packages like react or react-native are imported
connectToDevTools({...config});
}
```
> **NOTE** that this API (`connectToDevTools`) must be (1) run in the same context as React and (2) must be called before React packages are imported (e.g. `react`, `react-dom`, `react-native`).
### `initialize` arguments
| Argument | Description |
|---------------------------|-------------|
| `settings` | Optional. If not specified, or received as null, then default settings are used. Can be plain object or a Promise that resolves with the [plain settings object](#Settings). If Promise rejects, the console will not be patched and some console features from React DevTools will not work. |
| | en | en | en_0027_README | 0 | |
`shouldStartProfilingNow` | Optional. Whether to start profiling immediately after installing the hook. Defaults to `false`. |
| `profilingSettings` | Optional. Profiling settings used when `shouldStartProfilingNow` is `true`. Defaults to `{ recordChangeDescriptions: false, recordTimeline: false }`. |
| `componentFilters` | Optional. Array or Promise that resolves to an array of component filters to apply before DevTools connects. Defaults to the built-in host component filter. See [Component filters](#component-filters) for the full spec. |
#### `Settings`
| Spec | Default value |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <pre>{<br> appendComponentStack: boolean,<br> breakOnConsoleErrors: boolean,<br> showInlineWarningsAndErrors: boolean,<br> hideConsoleLogsInStrictMode: boolean,<br> disableSecondConsoleLogDimmingInStrictMode: boolean<br>}</pre> | <pre>{<br> appendComponentStack: true,<br> | en | en | en_0027_README | 1 | |
breakOnConsoleErrors: false,<br> showInlineWarningsAndErrors: true,<br> hideConsoleLogsInStrictMode: false,<br> disableSecondConsoleLogDimmingInStrictMode: false<br>}</pre> |
#### Component filters
Each filter object must include `type` and `isEnabled`. Some filters also require `value` or `isValid`.
| Type | Required fields | Description |
|------|-----------------|-------------|
| `ComponentFilterElementType` (`1`) | `type`, `isEnabled`, `value: ElementType` | Hides elements of the given element type. DevTools defaults to hiding host components. |
| `ComponentFilterDisplayName` (`2`) | `type`, `isEnabled`, `isValid`, `value: string` | Hides components whose display name matches the provided RegExp string. |
| `ComponentFilterLocation` (`3`) | `type`, `isEnabled`, `isValid`, `value: string` | Hides components whose source location matches the provided RegExp string. |
| `ComponentFilterHOC` (`4`) | `type`, `isEnabled`, `isValid` | Hides higher-order components. |
| `ComponentFilterEnvironmentName` (`5`) | `type`, `isEnabled`, `isValid`, `value: string` | Hides components whose environment name matches the provided string. |
| `ComponentFilterActivitySlice` (`6`) | `type`, `isEnabled`, `isValid`, `activityID`, `rendererID` | Filters activity slices; usually managed by DevTools rather than user code. |
### `connectToDevTools` options
| Prop | Default | Description |
|------------------------|---------------|---------------------------------------------------------------------------------------------------------------------------|
| | en | en | en_0027_README | 2 | |
`host` | `"localhost"` | Socket connection to frontend should use this host. |
| `isAppActive` | | (Optional) function that returns true/false, telling DevTools when it's ready to connect to React. |
| `path` | `""` | Path appended to the WebSocket URI (e.g. `"/__react_devtools__/"`). Useful when proxying through a reverse proxy on a subpath. A leading `/` is added automatically if missing. |
| `port` | `8097` | Socket connection to frontend should use this port. |
| `resolveRNStyle` | | (Optional) function that accepts a key (number) and returns a style (object); used by React Native. |
| `retryConnectionDelay` | `200` | Delay (ms) to wait between retrying a failed Websocket connection |
| `useHttps` | `false` | Socket connection to frontend should use secure protocol (wss). |
| `websocket` | | Custom `WebSocket` connection to frontend; overrides `host` and `port` settings. |
| | en | en | en_0027_README | 3 | |
`onSettingsUpdated` | | A callback that will be called when the user updates the settings in the UI. You can use it for persisting user settings. | |
### `connectWithCustomMessagingProtocol` options
| Prop | Description |
|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `onSubscribe` | Function, which receives listener (function, with a single argument) as an argument. Called when backend subscribes to messages from the other end (frontend). |
| `onUnsubscribe` | Function, which receives listener (function) as an argument. Called when backend unsubscribes to messages from the other end (frontend). |
| `onMessage` | Function, which receives 2 arguments: event (string) and payload (any). Called when backend emits a message, which should be sent to the frontend. |
| `onSettingsUpdated` | A callback that will be called when the user updates the settings in the UI. You can use it for persisting user settings. |
Unlike `connectToDevTools`, `connectWithCustomMessagingProtocol` returns a callback, which can be used for unsubscribing the backend from the global DevTools hook.
# Frontend API
Frontend APIs can be used to render the DevTools UI into a DOM node. One example of this is [`react-devtools`](https://github.com/facebook/react/tree/main/packages/react-devtools) which wraps DevTools in an Electron app.
| en | en | en_0027_README | 4 | |
### Example
```js
import DevtoolsUI from "react-devtools-core/standalone";
// See the full list of API methods in documentation below.
const { setContentDOMNode, startServer } = DevtoolsUI;
// Render DevTools UI into a DOM element.
setContentDOMNode(document.getElementById("container"));
// Start socket server used to communicate between backend and frontend.
startServer(
// Port defaults to 8097
1234,
// Host defaults to "localhost"
"example.devserver.com",
// Optional config for secure socket (WSS).
{
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
}
);
```
### Exported methods
The `default` export is an object defining the methods described below.
These methods support chaining for convenience. For example:
```js
const DevtoolsUI = require("react-devtools-core/standalone");
DevtoolsUI.setContentDOMNode(element).startServer();
```
#### `connectToSocket(socket: WebSocket)`
> This is an advanced config function that is typically not used.
Custom `WebSocket` connection to use for communication between DevTools frontend and backend. Calling this method automatically initializes the DevTools UI (similar to calling `startServer()`).
#### `openProfiler()`
Automatically select the "Profiler" tab in the DevTools UI.
#### `setContentDOMNode(element: HTMLElement)`
Set the DOM element DevTools UI should be rendered into on initialization.
#### `setDisconnectedCallback(callback: Function)`
_Optional_ callback to be notified when DevTools `WebSocket` closes (or errors).
| en | en | en_0027_README | 5 | |
#### `setProjectRoots(roots: Array<string>)`
_Optional_ set of root directories for source files. These roots can be used to open an inspected component's source code using an IDE.
#### `setStatusListener(callback: Function)`
_Optional_ callback to be notified of socket server events (e.g. initialized, errored, connected).
This callback receives two parameters:
```js
function onStatus(
message: string,
status: 'server-connected' | 'devtools-connected' | 'error'
): void {
// ...
}
```
#### `startServer(port?, host?, httpsOptions?, loggerOptions?, path?, clientOptions?)`
Start a socket server (used to communicate between backend and frontend) and renders the DevTools UI.
This method accepts the following parameters:
| Name | Default | Description |
|---|---|---|
| `port` | `8097` | Port the local server listens on. |
| `host` | `"localhost"` | Host the local server binds to. |
| `httpsOptions` | | _Optional_ object defining `key` and `cert` strings. |
| `loggerOptions` | | _Optional_ object defining a `surface` string (to be included with DevTools logging events). |
| `path` | | _Optional_ path to append to the WebSocket URI served to connecting clients (e.g. `"/__react_devtools__/"`). Also set via the `REACT_DEVTOOLS_PATH` env var in the Electron app. |
| `clientOptions` | | _Optional_ object with client-facing overrides (see below). |
##### `clientOptions`
| en | en | en_0027_README | 6 | |
When connecting through a reverse proxy, the client may need to connect to a different host, port, or protocol than the local server. Use `clientOptions` to override what appears in the `connectToDevTools()` script served to clients. Any field not set falls back to the corresponding server value.
| Field | Default | Description |
|---|---|---|
| `host` | server `host` | Host the client connects to. |
| `port` | server `port` | Port the client connects to. |
| `useHttps` | server `useHttps` | Whether the client should use `wss://`. |
These can also be set via environment variables in the Electron app:
| Env Var | Description |
|---|---|
| `REACT_DEVTOOLS_CLIENT_HOST` | Overrides the host in the served client script. |
| `REACT_DEVTOOLS_CLIENT_PORT` | Overrides the port in the served client script. |
| `REACT_DEVTOOLS_CLIENT_USE_HTTPS` | Set to `"true"` to make the served client script use `wss://`. |
##### Reverse proxy example
Run DevTools locally on the default port, but tell clients to connect through a remote proxy:
```sh
REACT_DEVTOOLS_CLIENT_HOST=remote.example.com \
REACT_DEVTOOLS_CLIENT_PORT=443 \
REACT_DEVTOOLS_CLIENT_USE_HTTPS=true \
REACT_DEVTOOLS_PATH=/__react_devtools__/ \
react-devtools
```
The server listens on `localhost:8097`. The served script tells clients:
```js
connectToDevTools({host: 'remote.example.com', port: 443, useHttps: true, path: '/__react_devtools__/'})
```
# Development
Watch for changes made to the backend entry point and rebuild:
```sh
yarn start:backend
```
Watch for changes made to the standalone UI entry point and rebuild:
```sh
yarn start:standalone
```
Run the standalone UI using `yarn start` in the [`react-devtools`](https://github.com/facebook/react/tree/main/packages/react-devtools).
| en | en | en_0027_README | 7 | |
# TypeScript
[](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/typescript)
[](https://www.npmjs.com/package/typescript)
[](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -D typescript
```
For our nightly builds:
```bash
npm install -D typescript@next
```
## Contribute
| en | en | en_0028_README | 0 | |
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Roadmap
For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).
| en | en | en_0028_README | 1 | |
# Read this!
The files within this directory are copied and deployed with TypeScript as the set of APIs available as a part of the JavaScript language.
There are three main domains of APIs in `src/lib`:
- **ECMAScript language features** - e.g. JavaScript APIs like functions on Array etc which are documented in [ECMA-262](https://tc39.es/ecma262/)
- **DOM APIs** - e.g. APIs which are available in web browsers
- **Intl APIs** - e.g. APIs scoped to `Intl` which are documented in [ECMA-402](https://www.ecma-international.org/publications-and-standards/standards/ecma-402/)
## How do we figure out when to add something?
TypeScript has a rule-of-thumb to only add something when it has got far enough through the standards process that it is more or less confirmed. For JavaScript APIs and language features, that means the proposal is at stage 3 or later.
You can find the source of truth for modern language features and Intl APIs in these completed proposal lists:
- [JavaScript](https://github.com/tc39/proposals/blob/master/finished-proposals.md)
- [Intl](https://github.com/tc39/proposals/blob/master/ecma402/finished-proposals.md)
For the DOM APIs, which are a bit more free-form, we have asked that APIs are available un-prefixed/flagged in at least 2 browser _engines_ (i.e. not just 2 chromium browsers.)
## Generated files
The DOM files ending in `.generated.d.ts` aren't meant to be edited by hand.
If you need to make changes to such files, make a change to the input files for [**our library generator**](https://github.com/microsoft/TypeScript-DOM-lib-generator).
| en | en | en_0029_README | 0 | |
# How does TypeScript formatting work?
To format code you need to have a formatting context and a `SourceFile`. The formatting context contains
all user settings like tab size, newline character, etc.
The end result of formatting is represented by TextChange objects which hold the new string content, and
the text to replace it with.
```ts
export interface TextChange {
span: TextSpan; // start, length
newText: string;
}
```
## Internals
Most of the exposed APIs internally are `format*` and they all set up and configure `formatSpan` which could be considered the root call for formatting. Span in this case refers to the range of
the sourcefile which should be formatted.
The formatSpan then uses a scanner (either with or without JSX support) which starts at the highest
node the covers the span of text and recurses down through the node's children.
| en | en | en_0030_README | 0 | |
As it recurses, `processNode` is called on the children setting the indentation is decided and passed
through into each of that node's children.
The meat of formatting decisions is made via `processPair`, the pair here being the current node and the previous node. `processPair` which mutates the formatting context to represent the current place in the scanner and requests a set of rules which can be applied to the items via `createRulesMap`.
There are a lot of rules, which you can find in [rules.ts](./rules.ts) each one has a left and right reference to nodes or token ranges and note of what action should be applied by the formatter.
### Where is this used?
The formatter is used mainly from any language service operation that inserts or modifies code. The formatter is not exported publicly, and so all usage can only come through the language server.
| en | en | en_0030_README | 1 | |
// === Auto Imports ===
```ts
// @Filename: /main.ts
/*|*/
```
## From completions
- `Component` from `"./Component"`
- `fromAtTypesFoo` from `"foo"`
- `fromBar` from `"bar"`
- `fromLocal` from `"./local"`
```ts
import { Component } from "./Component";
Component
```
```ts
import { fromAtTypesFoo } from "foo";
fromAtTypesFoo
```
```ts
import { fromBar } from "bar";
fromBar
```
```ts
import { fromLocal } from "./local";
fromLocal
```
| en | en | en_0031_autoImportAllowTsExtensions1.baseline | 0 | |
// === Auto Imports ===
```ts
// @Filename: /main.ts
/*|*/
```
## From completions
- `Component` from `"./Component.tsx"`
- `fromAtTypesFoo` from `"foo"`
- `fromBar` from `"bar"`
- `fromLocal` from `"./local.ts"`
```ts
import { Component } from "./Component.tsx";
Component
```
```ts
import { fromAtTypesFoo } from "foo";
fromAtTypesFoo
```
```ts
import { fromBar } from "bar";
fromBar
```
```ts
import { fromLocal } from "./local.ts";
fromLocal
```
| en | en | en_0032_autoImportAllowTsExtensions2.baseline | 0 | |
// === Auto Imports ===
```ts
// @Filename: /main.ts
import { Component } from "./Component.tsx";
/*|*/
```
## From completions
- `fromDecl` from `"./decl"`
- `fromLocal` from `"./local.ts"`
```ts
import { Component } from "./Component.tsx";
import { fromDecl } from "./decl";
fromDecl
```
```ts
import { Component } from "./Component.tsx";
import { fromLocal } from "./local.ts";
fromLocal
```
| en | en | en_0033_autoImportAllowTsExtensions3.baseline | 0 | |
// === Auto Imports ===
```ts
// @Filename: /main.ts
import { Component } from "./local.js";
/*|*/
```
## From completions
- `fromDecl` from `"./decl.js"`
- `fromLocal` from `"./local.js"`
```ts
import { fromDecl } from "./decl.js";
import { Component } from "./local.js";
fromDecl
```
```ts
import { Component, fromLocal } from "./local.js";
fromLocal
```
| en | en | en_0034_autoImportAllowTsExtensions4.baseline | 0 | |
// === Auto Imports ===
```ts
// @Filename: /a.ts
/*|*/
```
## From completions
- `coolName` from `"./cool-name"`
- `explode` from `"./cool-name"`
- `isAbsolute` from `"path"`
- `join` from `"path"`
- `normalize` from `"path"`
- `path` from `"path"`
- `resolve` from `"path"`
```ts
import coolName = require("./cool-name");
coolName
```
```ts
import coolName = require("./cool-name");
coolName.explode
```
```ts
import path = require("path");
path.isAbsolute
```
```ts
import path = require("path");
path.join
```
```ts
import path = require("path");
path.normalize
```
```ts
import path = require("path");
path
```
```ts
import path = require("path");
path.resolve
```
| en | en | en_0035_autoImportVerbatimCJS1.baseline | 0 | |
## From codefixes
### When marker text is `normalize`
Add import from "path"
```ts
import path = require("path");
path.normalize
```
### When marker text is `join`
Add import from "path"
```ts
import path = require("path");
path.join
```
### When marker text is `path`
Add import from "path"
```ts
import path = require("path");
path
```
### When marker text is `explode`
Add import from "./cool-name"
```ts
import coolName = require("./cool-name");
coolName.explode
```
| en | en | en_0035_autoImportVerbatimCJS1.baseline | 1 | |
# Note
🚨 **Important** 🚨: All code changes should be submitted to the https://github.com/microsoft/typescript-go repo. Development in this codebase [is winding down](https://devblogs.microsoft.com/typescript/progress-on-typescript-7-december-2025/#typescript-6.0-is-the-last-javascript-based-release) and PRs will only be merged if they fix **critical** 6.0 issues (at minimum, any bug that existed in 5.9 is not critical unless it's a security issue).
# Instructions for Logging Issues
## 1. Read the FAQ
Please [read the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) before logging new issues, even if you think you have found a bug.
Issues that ask questions answered in the FAQ will be closed without elaboration.
## 2. Search for Duplicates
[Search the existing issues in GitHub](https://github.com/Microsoft/TypeScript/search?type=Issues) or by the query `site:github.com/microsoft/TypeScript <your keywords>` in your favorite search engine before logging a new one. Search engines generally list more relevant and accurate results at the top than the GitHub searching feature.
Some search tips:
* *Don't* restrict your search to only open issues. An issue with a title similar to yours may have been closed as a duplicate of one with a less-findable title.
* Check for synonyms. For example, if your bug involves an interface, it likely also occurs with type aliases or classes.
* Search for the title of the issue you're about to log. This sounds obvious but 80% of the time this is sufficient to find a duplicate when one exists.
* Read more than the first page of results. Many bugs here use the same words so relevancy sorting is not particularly strong.
| en | en | en_0036_CONTRIBUTING | 0 | |
* If you have a crash, search for the first few topmost function names shown in the call stack.
## 3. Do you have a question?
The issue tracker is for **issues**, in other words, bugs and suggestions.
If you have a *question*, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources.
Due to increased traffic, we can no longer answer questions in the issue tracker.
## 4. Did you find a bug?
When logging a bug, please be sure to include the following:
* What version of TypeScript you're using (run `tsc --v`)
* If at all possible, an *isolated* way to reproduce the behavior
* The behavior you expect to see, and the actual behavior
You can try out the nightly build of TypeScript (`npm install typescript@next`) to see if the bug has already been fixed.
## 5. Do you have a suggestion?
We also accept suggestions in the issue tracker.
Be sure to [check the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) and [search](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) first.
In general, things we find useful when reviewing suggestions are:
* A description of the problem you're trying to solve
* An overview of the suggested solution
* Examples of how the suggestion would work in various places
* Code examples showing e.g. "this would be an error, this wouldn't"
* Code examples showing the generated JavaScript (if applicable)
* If relevant, precedent in other languages can be useful for establishing context and expected behavior
| en | en | en_0036_CONTRIBUTING | 1 | |
# Instructions for Contributing Code (Legacy)
## What You'll Need
0. [A bug or feature you want to work on](https://github.com/microsoft/TypeScript/issues?q=is%3Aissue%20label%3A%22Help%20Wanted%22)!
1. [A GitHub account](https://github.com/join).
2. A copy of the TypeScript code. See the next steps for instructions.
3. [Node](https://nodejs.org), which runs JavaScript locally. Current or LTS will both work.
4. An editor. [VS Code](https://code.visualstudio.com) is the best place to start for TypeScript.
5. The hereby command line tool, for building and testing changes. See the next steps for how to install it.
## Get Started
1. Install node using the version you downloaded from [nodejs.org](https://nodejs.org).
2. Open a terminal.
3. Make a fork—your own copy—of TypeScript on your GitHub account, then make a clone—a local copy—on your computer. ([Here are some step-by-step instructions](https://github.com/anitab-org/mentorship-android/wiki/Fork%2C-Clone-%26-Remote)). Add `--depth=1` to the end of the `git clone` command to save time.
4. Install the hereby command line tool: `npm install -g hereby`
5. Change to the TypeScript folder you made: `cd TypeScript`
6. Install dependencies: `npm ci`
7. Make sure everything builds and tests pass: `hereby runtests-parallel`
8. Open the TypeScript folder in your editor.
9. Follow the directions below to add and debug a test.
## Helpful tasks
Running `hereby --tasks` provides the full listing, but here are a few common tasks you might use.
| en | en | en_0036_CONTRIBUTING | 2 | |
```
hereby local # Build the compiler into built/local.
hereby clean # Delete the built compiler.
hereby LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
hereby tests # Build the test infrastructure using the built compiler.
hereby runtests # Run tests using the built compiler and test infrastructure.
# You can override the specific suite runner used or specify a test for this command.
# Use --tests=<testPath> for a specific test and/or --runner=<runnerName> for a specific suite.
# Valid runners include conformance, compiler, fourslash, and project
hereby runtests-parallel # Like runtests, but split across multiple threads. Uses a number of threads equal to the system
# core count by default. Use --workers=<number> to adjust this.
hereby baseline-accept # This replaces the baseline test results with the results obtained from hereby runtests.
hereby lint # Runs eslint on the TypeScript source.
hereby help # List the above commands.
```
## Tips
### Using a development container
If you prefer to develop using containers, this repository includes a [development container](https://code.visualstudio.com/docs/remote/containers) that you can use to quickly create an isolated development environment with all the tools you need to start working on TypeScript. To get started with a dev container and VS Code, either:
| en | en | en_0036_CONTRIBUTING | 3 | |
- Clone the TypeScript repository locally and use the `Open Folder in Container` command.
- Use the `Clone Repository in Container Volume` command to clone the TypeScript repository into a new container.
### Faster clones
The TypeScript repository is relatively large. To save some time, you might want to clone it without the repo's full history using `git clone --depth=1`.
### Filename too long on Windows
You might need to run `git config --global core.longpaths true` before cloning TypeScript on Windows.
### Using local builds
Run `hereby` to build a version of the compiler/language service that reflects changes you've made. You can then run `node <repo-root>/built/local/tsc.js` in place of `tsc` in your project. For example, to run `tsc --watch` from within the root of the repository on a file called `test.ts`, you can run `node ./built/local/tsc.js --watch test.ts`.
## Contributing bug fixes
TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) or in the "Backlog milestone") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort.
## Contributing features
| en | en | en_0036_CONTRIBUTING | 4 | |
Features (things that add new or improved functionality to TypeScript) may be accepted, but will need to first be approved (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) or in the "Backlog" milestone) by a TypeScript project maintainer in the suggestion issue. Features with language design impact, or that are adequately satisfied with external tools, will not be accepted.
## Issue claiming
If you intend to work on an issue, please avoid leaving comments like "I'm going to work on this". There are a few reasons for this. These comments tend to [discourage anyone from working in the area](https://devblogs.microsoft.com/oldnewthing/20091201-00/?p=15843), yet many issues are much more difficult than they first appear, and you might find yourself trying to fix several issues before finding one that can be completed. Many issues have a long trail of people indicating that they're going to try to fix it, but no PR.
Conversely, you do not need to ask anyone's permission before starting work on an issue marked as "help wanted". It's always fine to try! We ask that you choose issues tagged in the "Backlog" milestone as these are issues that we've identified as needing fixes / implementations.
The sheer quantity of open issues, combined with their general difficulty, makes it extremely unlikely that you and another contributor are a) working on the same issue and b) both going to find a solution.
## Legal
You will need to complete a Contributor License Agreement (CLA). Briefly, this agreement testifies that you are granting us permission to use the submitted change according to the terms of the project's license, and that the work being submitted is under appropriate copyright. Upon submitting a pull request, you will automatically be given instructions on how to sign the CLA.
## Housekeeping
| en | en | en_0036_CONTRIBUTING | 5 | |
Your pull request should:
* Include a description of what your change intends to do
* Be based on reasonably recent commit in the **main** branch
* Include adequate tests
* At least one test should fail in the absence of your non-test code changes. If your PR does not match this criteria, please specify why
* Tests should include reasonable permutations of the target fix/change
* Include baseline changes with your change
* Follow the code conventions described in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration
## Force-pushing
Avoid force-pushing your changes, especially when updating your PR based on review feedback. Force-pushed changes are not easily viewable on GitHub, and not at all viewable if a force-push also rebases against main. TypeScript PRs are squash merged, so the specific commits on your PR branch do not matter, only the PR title itself. Don't worry about having a perfect commit history; instead focus on making your changes as easy to review and merge as possible.
## Contributing `lib.d.ts` fixes
There are three relevant locations to be aware of when it comes to TypeScript's library declaration files:
* `src/lib`: the location of the sources themselves.
* `lib`: the location of the last-known-good (LKG) versions of the files which are updated periodically.
* `built/local`: the build output location, including where `src/lib` files will be copied to.
| en | en | en_0036_CONTRIBUTING | 6 | |
Any changes should be made to [src/lib](https://github.com/Microsoft/TypeScript/tree/main/src/lib). **Most** of these files can be updated by hand, with the exception of any generated files (see below).
Library files in `built/local/` are updated automatically by running the standard build task:
```sh
hereby
```
The files in `lib/` are used to bootstrap compilation and usually **should not** be updated unless publishing a new version or updating the LKG.
### Modifying generated library files
The files `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` both represent type declarations for the DOM and are auto-generated. To make any modifications to them, you will have to direct changes to https://github.com/Microsoft/TSJS-lib-generator
## Documentation on TypeScript Compiler
If you need a head start understanding how the compiler works, or how the code in different parts of the compiler works, there is a separate repo: [TypeScript Compiler Notes](https://github.com/microsoft/TypeScript-Compiler-Notes). As the name implies, it contains notes understood by different engineers about different parts of the compiler.
## Running the Tests
To run all tests, invoke the `runtests-parallel` target using hereby:
```Shell
hereby runtests-parallel
```
This will run all tests; to run only a specific subset of tests, use:
```Shell
hereby runtests --tests=<regex>
```
e.g. to run all compiler baseline tests:
```Shell
hereby runtests --tests=compiler
```
or to run a specific test: `tests\cases\compiler\2dArrays.ts`
```Shell
hereby runtests --tests=2dArrays
```
## Debugging the tests
| en | en | en_0036_CONTRIBUTING | 7 | |
You can debug with VS Code or Node instead with `hereby runtests -i`:
```Shell
hereby runtests --tests=2dArrays -i
```
You can also use the [provided VS Code launch configuration](./.vscode/launch.template.json) to launch a debug session for an open test file. Rename the file 'launch.json', open the test file of interest, and launch the debugger from the debug panel (or press F5).
## Adding a Test
To add a new test case, add a `.ts` file in `tests\cases\compiler` with code that shows the bug is now fixed, or your new feature now works.
These files support metadata tags in the format `// @metaDataName: value`.
The supported names and values are the same as those supported in the compiler itself, with the addition of the `fileName` flag.
`fileName` tags delimit sections of a file to be used as separate compilation units.
They are useful for testing modules.
See below for examples.
**Note** that if you have a test corresponding to a specific area of spec compliance, you can put it in the appropriate subfolder of `tests\cases\conformance`.
**Note** that test filenames must be distinct from all other test names, so you may have to work a bit to find a unique name if it's something common.
### Tests for multiple files
When you need to mimic having multiple files in a single test to test features such as "import", use the `filename` tag:
```ts
// @filename: file1.ts
export function f() {
}
// @filename: file2.ts
import { f as g } from "file1";
var x = g();
```
## Managing the baselines
Most tests generate "baselines" to find differences in output.
As an example, compiler tests usually emit one file each for
| en | en | en_0036_CONTRIBUTING | 8 | |
- the `.js` and `.d.ts` output (all in the same `.js` output file),
- the errors produced by the compiler (in an `.errors.txt` file),
- the types of each expression (in a `.types` file),
- the symbols for each identifier (in a `.symbols` file), and
- the source map outputs for files if a test opts into them (in a `.js.map` file).
When a change in the baselines is detected, the test will fail. To inspect changes vs the expected baselines, use
```Shell
git diff --diff-filter=AM --no-index ./tests/baselines/reference ./tests/baselines/local
```
Alternatively, you can set the `DIFF` environment variable and run `hereby diff`, or manually run your favorite folder diffing tool between `tests/baselines/reference` and `tests/baselines/local`. Our team largely uses Beyond Compare and WinMerge.
After verifying that the changes in the baselines are correct, run
```Shell
hereby baseline-accept
```
This will change the files in `tests\baselines\reference`, which should be included as part of your commit.
Be sure to validate the changes carefully -- apparently unrelated changes to baselines can be clues about something you didn't think of.
## Localization
All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json).
If you make changes to it, run `hereby generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`.
See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages).
| en | en | en_0036_CONTRIBUTING | 9 | |
# canWatchAffectingLocation
Determines if package.json that was found during module resolution and change in it will affect resolution can be watched.
## Testing for Dos root: c:/
| File | canWatchAffectingLocation |
| ----------------------------------------------------------------------------------- | ------------------------- |
| c:/package.json | false |
| c:/folderAtRoot/package.json | true |
| c:/folderAtRoot/folder1/package.json | true |
| c:/folderAtRoot/folder1/folder2/package.json | true |
| c:/folderAtRoot/folder1/folder2/folder3/package.json | true |
| c:/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| c:/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| c:/users/package.json | false |
| c:/users/username/package.json | false |
| c:/users/username/folderAtRoot/package.json | true |
| c:/users/username/folderAtRoot/folder1/package.json | true |
| c:/users/username/folderAtRoot/folder1/folder2/package.json | true |
| c:/users/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| | en | en | en_0037_canWatchAffectingLocationDos.baseline | 0 | |
c:/users/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| c:/users/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| c:/user/package.json | true |
| c:/user/username/package.json | true |
| c:/user/username/folderAtRoot/package.json | true |
| c:/user/username/folderAtRoot/folder1/package.json | true |
| c:/user/username/folderAtRoot/folder1/folder2/package.json | true |
| c:/user/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| c:/user/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| c:/user/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| c:/usr/package.json | true |
| c:/usr/username/package.json | true |
| c:/usr/username/folderAtRoot/package.json | true |
| c:/usr/username/folderAtRoot/folder1/package.json | true |
| c:/usr/username/folderAtRoot/folder1/folder2/package.json | true |
| c:/usr/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| c:/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| | en | en | en_0037_canWatchAffectingLocationDos.baseline | 1 | |
c:/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| c:/home/package.json | true |
| c:/home/username/package.json | true |
| c:/home/username/folderAtRoot/package.json | true |
| c:/home/username/folderAtRoot/folder1/package.json | true |
| c:/home/username/folderAtRoot/folder1/folder2/package.json | true |
| c:/home/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| c:/home/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| c:/home/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| c:/workspaces/package.json | true |
| c:/workspaces/folderAtRoot/package.json | true |
| c:/workspaces/folderAtRoot/folder1/package.json | true |
| c:/workspaces/folderAtRoot/folder1/folder2/package.json | true |
| c:/workspaces/folderAtRoot/folder1/folder2/folder3/package.json | true |
| c:/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| c:/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| en | en | en_0037_canWatchAffectingLocationDos.baseline | 2 | |
# canWatchAffectingLocation
Determines if package.json that was found during module resolution and change in it will affect resolution can be watched.
## Testing for Posix root: /
| File | canWatchAffectingLocation |
| --------------------------------------------------------------------------------- | ------------------------- |
| /package.json | false |
| /folderAtRoot/package.json | false |
| /folderAtRoot/folder1/package.json | false |
| /folderAtRoot/folder1/folder2/package.json | true |
| /folderAtRoot/folder1/folder2/folder3/package.json | true |
| /folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| /folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| /users/package.json | false |
| /users/username/package.json | false |
| /users/username/folderAtRoot/package.json | true |
| /users/username/folderAtRoot/folder1/package.json | true |
| /users/username/folderAtRoot/folder1/folder2/package.json | true |
| /users/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| | en | en | en_0038_canWatchAffectingLocationPosix.baseline | 0 | |
/users/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| /users/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| /user/package.json | false |
| /user/username/package.json | false |
| /user/username/folderAtRoot/package.json | true |
| /user/username/folderAtRoot/folder1/package.json | true |
| /user/username/folderAtRoot/folder1/folder2/package.json | true |
| /user/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| /user/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| /user/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| /usr/package.json | false |
| /usr/username/package.json | false |
| /usr/username/folderAtRoot/package.json | true |
| /usr/username/folderAtRoot/folder1/package.json | true |
| /usr/username/folderAtRoot/folder1/folder2/package.json | true |
| /usr/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| /usr/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| | en | en | en_0038_canWatchAffectingLocationPosix.baseline | 1 | |
/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| /home/package.json | false |
| /home/username/package.json | false |
| /home/username/folderAtRoot/package.json | true |
| /home/username/folderAtRoot/folder1/package.json | true |
| /home/username/folderAtRoot/folder1/folder2/package.json | true |
| /home/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| /home/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| /home/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| /workspaces/package.json | false |
| /workspaces/folderAtRoot/package.json | true |
| /workspaces/folderAtRoot/folder1/package.json | true |
| /workspaces/folderAtRoot/folder1/folder2/package.json | true |
| /workspaces/folderAtRoot/folder1/folder2/folder3/package.json | true |
| /workspaces/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| /workspaces/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| en | en | en_0038_canWatchAffectingLocationPosix.baseline | 2 | |
# canWatchAffectingLocation
Determines if package.json that was found during module resolution and change in it will affect resolution can be watched.
## Testing for Unc root: //vda1cs4850/
| File | canWatchAffectingLocation |
| --------------------------------------------------------------------------------------------- | ------------------------- |
| //vda1cs4850/package.json | false |
| //vda1cs4850/folderAtRoot/package.json | false |
| //vda1cs4850/folderAtRoot/folder1/package.json | false |
| //vda1cs4850/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/users/package.json | false |
| //vda1cs4850/users/username/package.json | false |
| | en | en | en_0039_canWatchAffectingLocationUnc.baseline | 0 | |
//vda1cs4850/users/username/folderAtRoot/package.json | true |
| //vda1cs4850/users/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/users/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/users/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/users/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/users/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/user/package.json | false |
| //vda1cs4850/user/username/package.json | false |
| //vda1cs4850/user/username/folderAtRoot/package.json | true |
| //vda1cs4850/user/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/user/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/user/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/user/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| | en | en | en_0039_canWatchAffectingLocationUnc.baseline | 1 | |
//vda1cs4850/user/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/usr/package.json | false |
| //vda1cs4850/usr/username/package.json | false |
| //vda1cs4850/usr/username/folderAtRoot/package.json | true |
| //vda1cs4850/usr/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/usr/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/usr/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/home/package.json | false |
| //vda1cs4850/home/username/package.json | false |
| //vda1cs4850/home/username/folderAtRoot/package.json | true |
| | en | en | en_0039_canWatchAffectingLocationUnc.baseline | 2 | |
//vda1cs4850/home/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/home/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/home/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/home/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/home/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/workspaces/package.json | false |
| //vda1cs4850/workspaces/folderAtRoot/package.json | true |
| //vda1cs4850/workspaces/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/workspaces/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/workspaces/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| en | en | en_0039_canWatchAffectingLocationUnc.baseline | 3 | |
# canWatchAffectingLocation
Determines if package.json that was found during module resolution and change in it will affect resolution can be watched.
## Testing for UncDos root: //vda1cs4850/c$
| File | canWatchAffectingLocation |
| ------------------------------------------------------------------------------------------------ | ------------------------- |
| //vda1cs4850/c$/package.json | false |
| //vda1cs4850/c$/folderAtRoot/package.json | true |
| //vda1cs4850/c$/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/c$/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/c$/users/package.json | false |
| //vda1cs4850/c$/users/username/package.json | false |
| | en | en | en_0040_canWatchAffectingLocationUncDos.baseline | 0 | |
//vda1cs4850/c$/users/username/folderAtRoot/package.json | true |
| //vda1cs4850/c$/users/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/users/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/users/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/users/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/c$/users/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/c$/user/package.json | true |
| //vda1cs4850/c$/user/username/package.json | true |
| //vda1cs4850/c$/user/username/folderAtRoot/package.json | true |
| //vda1cs4850/c$/user/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/user/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/user/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/user/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| | en | en | en_0040_canWatchAffectingLocationUncDos.baseline | 1 | |
//vda1cs4850/c$/user/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/c$/usr/package.json | true |
| //vda1cs4850/c$/usr/username/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/c$/usr/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/c$/home/package.json | true |
| //vda1cs4850/c$/home/username/package.json | true |
| //vda1cs4850/c$/home/username/folderAtRoot/package.json | true |
| | en | en | en_0040_canWatchAffectingLocationUncDos.baseline | 2 | |
//vda1cs4850/c$/home/username/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/home/username/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/home/username/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/home/username/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/c$/home/username/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| //vda1cs4850/c$/workspaces/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/folder1/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/folder1/folder2/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/folder1/folder2/folder3/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/package.json | true |
| //vda1cs4850/c$/workspaces/folderAtRoot/folder1/folder2/folder3/folder4/folder5/package.json | true |
| en | en | en_0040_canWatchAffectingLocationUncDos.baseline | 3 |