### Gulpfile Setup with Custom Subtask Source: https://github.com/microsoft/rushstack/wiki/Gulp-Core-Build This example shows a typical gulpfile setup using gulp-core-build, including importing necessary tasks and defining a custom subtask using `build.subTask`. It then integrates this custom subtask into the main build process. ```javascript 'use strict'; // Import core build. let build = require('gulp-core-build'); // Import the tasks. let lint = require('gulp-core-build-typescript').tslint; let typescript = require('gulp-core-build-typescript').typescript; let sass = require('gulp-core-build-sass').default; let karma = require('gulp-core-build-karma').default; let webpack = require('gulp-core-build-webpack').default; let serve = require('gulp-core-build-serve').default; // Shorthand for defining custom subtasks // The proper method for this is to introduce a new package which exports a class that extends GulpTask // However, this shorthand allows an easy way to introduce one-off subtasks directly in the gulpfile let helloWorldSubtask = build.subTask('do-hello-world-subtask', function(gulp, buildOptions, done) { this.log('Hello, World!'); // use functions from GulpTask }); // Define gulp tasks. let buildTasks = build.task('build', build.parallel(helloWorldSubtask, lint, typescript, sass)); let testTasks = build.task('test', build.serial(buildTasks, karma)); let bundleTasks = build.task('bundle', build.serial(buildTasks, webpack)); let serveTasks = build.task('serve', build.serial(bundleTasks, serve)); let helloWorldTasks = build.task('hello-world', helloWorldSubtask); let defaultTasks = build.task('default', testTasks); // Tell the build to set up gulp tasks with the given gulp instance. build.initialize(require('gulp')); ``` -------------------------------- ### Clone and Build Rushstack Projects Source: https://github.com/microsoft/rushstack/blob/main/apps/rush/README.md Demonstrates cloning the Rushstack repository and using Rush to install dependencies and build the projects. The `rush install` and `rush build` commands are often instantaneous after the initial setup. ```bash $ git clone https://github.com/microsoft/rushstack $ cd rushstack $ rush install $ rush install # <-- instantaneous! $ rush rebuild $ rush build # <-- instantaneous! ``` -------------------------------- ### Install and Initialize Rush Source: https://context7.com/microsoft/rushstack/llms.txt Install Rush globally and initialize a new Rush monorepo. Use `rush install` to manage dependencies. ```bash # Install Rush globally npm install -g @microsoft/rush # Initialize a new Rush monorepo rush init # Install all dependencies for every project in the monorepo rush install ``` -------------------------------- ### Manually Load Rush SDK with Progress Notification Source: https://github.com/microsoft/rushstack/blob/main/libraries/rush-sdk/README.md This example demonstrates how to manually load the Rush SDK using the loader API. It allows monitoring installation progress via callbacks and specifies the starting folder for finding rush.json. ```ts import { RushSdkLoader, ISdkCallbackEvent } from '@rushstack/rush-sdk/loader'; if (!RushSdkLoader.isLoaded) { await RushSdkLoader.loadAsync({ // the search for rush.json starts here: rushJsonSearchFolder: "path/to/my-repo/apps/my-app", onNotifyEvent: (event: ISdkCallbackEvent) => { if (event.logMessage) { // Your tool can show progress about the loading: if (event.logMessage.kind === 'info') { console.log(event.logMessage.text); } } } }); } // Any subsequent attempts to call require() will return the same instance // that was loaded above. const rushSdk = require('@rushstack/rush-sdk'); const config = rushSdk.RushConfiguration.loadFromDefaultLocation(); ``` -------------------------------- ### Install Rush Stack VS Code Extension Source: https://github.com/microsoft/rushstack/blob/main/vscode-extensions/rush-vscode-extension/README.md Install the extension directly within VS Code using the provided command. This is the recommended method for quick setup. ```plaintext ext install RushStack.rushstack ``` -------------------------------- ### Manually Load Rush SDK with Abort Signal and Progress Bar Source: https://github.com/microsoft/rushstack/blob/main/libraries/rush-sdk/README.md This advanced example shows how to load the Rush SDK with an AbortController to cancel the operation and a callback to display a progress bar based on installation progress. ```ts import { RushSdkLoader, ISdkCallbackEvent } from '@rushstack/rush-sdk/loader'; // Use an AbortController to cancel the operation after a certain time period const abortController = new AbortController(); setTimeout(() => { abortController.abort(); }, 1000); if (!RushSdkLoader.isLoaded) { await RushSdkLoader.loadAsync({ // the search for rush.json starts here: rushJsonSearchFolder: "path/to/my-repo/apps/my-app", abortSignal: abortController.signal, onNotifyEvent: (event: ISdkCallbackEvent) => { if (event.logMessage) { // Your tool can show progress about the loading: if (event.logMessage.kind === 'info') { console.log(event.logMessage.text); } } if (event.progressPercent !== undefined) { // If installation takes a long time, your tool can display a progress bar displayYourProgressBar(event.progressPercent); } } }); } // Any subsequent attempts to call require() will return the same instance // that was loaded above. const rushSdk = require('@rushstack/rush-sdk'); const config = rushSdk.RushConfiguration.loadFromDefaultLocation(); ``` -------------------------------- ### Project rush-project.json Example Configuration Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/project-configuration.md Provides project-specific configuration, such as build cache settings. This example configures the 'build' operation. ```json { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/rush-project.schema.json", "operationSettings": [ { "operationName": "build", "outputFolderNames": ["dist"], "disableBuildCacheForOperation": false } ] } ``` -------------------------------- ### Install Project Dependencies with Rush Source: https://github.com/microsoft/rushstack/wiki/Contributing-to-this-repo Navigates into the cloned repository and installs all necessary package dependencies using the Rush install command. ```bash C:\Repos>cd web-build-tools C:\Repos\web-build-tools>rush install ``` -------------------------------- ### Install and View Help for trace-import Source: https://github.com/microsoft/rushstack/blob/main/apps/trace-import/README.md Installs the trace-import package globally using npm and displays the command-line help information. ```bash npm install -g @rushstack/trace-import trace-import --help ``` -------------------------------- ### Conventional Rush Install Workflow Source: https://github.com/microsoft/rushstack/blob/main/common/docs/rfcs/rfc-4230-rush-subspaces.md Demonstrates the standard workflow for installing dependencies and building projects in a conventional Rush monorepo. This process involves a single `rush install` command followed by `rush build`. ```bash rush install ``` ```bash rush build --to my-app ``` -------------------------------- ### Install and Use cpu-profile-summarizer Source: https://github.com/microsoft/rushstack/blob/main/apps/cpu-profile-summarizer/README.md Install the package globally using npm and then use the command-line tool to process cpuprofile files. Specify the input folder containing the files and the output TSV file path. ```bash # Install the NPM package npm install -g @rushstack/cpu-profile-summarizer # Process a folder of cpuprofile files into a summary tsv file cpu-profile-summarizer --input FOLDER --output FILE.tsv ``` -------------------------------- ### Install set-webpack-public-path-plugin Source: https://github.com/microsoft/rushstack/blob/main/webpack/set-webpack-public-path-plugin/README.md Install the plugin using npm. ```bash npm install @rushstack/set-webpack-public-path-plugin --save-dev ``` -------------------------------- ### Prepare Monorepo and Launch Lockfile Explorer Source: https://github.com/microsoft/rushstack/blob/main/apps/lockfile-explorer/README.md Navigate to your monorepo directory, ensure the common/temp/node_modules are up-to-date by running 'rush install' (or 'pnpm install' for non-Rush PNPM workspaces), and then launch the Lockfile Explorer CLI. The 'lfx' alias can be used as a shorthand for 'lockfile-explorer'. ```bash cd my-rush-repo rush install lockfile-explorer ``` -------------------------------- ### Example Project Structure Source: https://github.com/microsoft/rushstack/blob/main/libraries/rig-package/README.md Illustrates a typical project structure with multiple configuration files that can be centralized. ```plaintext project1/package.json project1/config/api-extractor.json project1/config/other-tool2.json project1/config/other-tool3.json project1/src/index.ts project2/package.json project2/config/api-extractor.json project2/config/other-tool2.json project2/config/other-tool3.json project2/src/index.ts project3/package.json project3/config/api-extractor.json project3/config/other-tool2.json project3/config/other-tool3.json project3/src/index.ts ``` -------------------------------- ### Workspace Linking Behavior Example Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/dependency-management.md Illustrates how Rush creates symlinks in the node_modules directory after running 'rush install', linking to actual project folders within the monorepo. ```bash # After running rush install # Rush creates apps/my-app/node_modules/@my-scope/ ├── my-lib -> ../../libraries/my-lib └── other-lib -> ../../libraries/other-lib ``` -------------------------------- ### Start and Stop Local S3 Endpoint Source: https://github.com/microsoft/rushstack/blob/main/build-tests/rush-amazon-s3-build-cache-plugin-integration-test/README.md Use these commands to manage the local min.io S3 endpoint for integration testing. Ensure Docker and docker-compose are installed. ```bash # start the docker container: docker-compose up -d # build the code: rushx build rushx read-s3-object ``` ```bash docker-compose up -d ``` ```bash docker-compose down ``` -------------------------------- ### Install and Launch Lockfile Explorer Source: https://context7.com/microsoft/rushstack/llms.txt Install the lockfile-explorer globally and run it from your monorepo root after 'rush install' to visualize PNPM lockfile dependencies. ```bash # Install globally npm install -g @rushstack/lockfile-explorer # Navigate to your Rush/PNPM monorepo root, then: rush install # Launch the Lockfile Explorer (alias: lfx) lockfile-explorer # or lfx # The tool starts at http://localhost: and opens your browser automatically. # It reads: # common/config/rush/pnpm-lock.yaml # common/config/rush/.pnpmfile.cjs # Each project's package.json ``` -------------------------------- ### Install @rushstack/hashed-folder-copy-plugin Source: https://github.com/microsoft/rushstack/blob/main/webpack/hashed-folder-copy-plugin/README.md Install the plugin as a development dependency using npm. ```bash npm install @rushstack/hashed-folder-copy-plugin --save-dev ``` -------------------------------- ### Install @rushstack/eslint-config Source: https://context7.com/microsoft/rushstack/llms.txt Install the necessary packages for using @rushstack/eslint-config. ```bash npm install --save-dev eslint typescript @rushstack/eslint-config ``` -------------------------------- ### Install @microsoft/load-themed-styles with npm Source: https://github.com/microsoft/rushstack/blob/main/libraries/load-themed-styles/README.md Use npm to install the package. This command adds the library to your project's dependencies. ```bash npm install --save @microsoft/load-themed-styles ``` -------------------------------- ### Install Dependencies with rush install Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/core-commands.md Installs dependencies based on the existing shrinkwrap file without modifying it. This command is suitable for CI environments to ensure dependency version consistency. ```bash rush install # Standard install rush install --production # Install only production deps ``` -------------------------------- ### Install ESLint Bulk CLI Source: https://github.com/microsoft/rushstack/blob/main/eslint/eslint-patch/README.md Globally install the @rushstack/eslint-bulk CLI for managing .eslint-bulk-suppressions.json files. ```bash npm install --global @rushstack/eslint-bulk ``` -------------------------------- ### Install @rushstack/loader-raw-script Source: https://github.com/microsoft/rushstack/blob/main/webpack/loader-raw-script/README.md Install the loader as a development dependency using npm. ```bash npm install @rushstack/loader-raw-script --save-dev ``` -------------------------------- ### Install Rush Globally Source: https://github.com/microsoft/rushstack/blob/main/apps/rush/README.md Install the Rush tool globally using npm. This command is typically run once to set up Rush on your system. ```bash $ npm install -g @microsoft/rush ``` -------------------------------- ### Install and Run Heft Source: https://context7.com/microsoft/rushstack/llms.txt Install Heft as a dev dependency and run common build tasks. ```bash # Install Heft npm install --save-dev @rushstack/heft # Build the project (compile + lint + api-extractor, etc.) heft build # Build and watch for changes heft build-watch # Run tests heft test # Clean build artifacts heft build --clean ``` -------------------------------- ### Help Output for Push Action Source: https://github.com/microsoft/rushstack/blob/main/libraries/ts-command-line/README.md Example of the auto-generated help documentation for a specific action (push) when invoked with --help. ```text usage: widget push [-h] [-f] [--protocol {ftp,webdav,scp}] Here we provide a longer description of how our action works. Optional arguments: -h, --help Show this help message and exit. -f, --force Push and overwrite any existing state --protocol {ftp,webdav,scp} Specify the protocol to use. This parameter may alternatively specified via the WIDGET_PROTOCOL environment variable. The default value is "scp". ``` -------------------------------- ### Install Lockfile Explorer Globally Source: https://github.com/microsoft/rushstack/blob/main/apps/lockfile-explorer/README.md Install the NPM package globally using npm, pnpm, or yarn. Ensure you use the same package manager for global installations to avoid conflicts. ```bash npm install -g @rushstack/lockfile-explorer ``` -------------------------------- ### Command-line.json Example Configuration Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/project-configuration.md Defines custom commands, their summaries, and parameters for the Rush CLI. Supports bulk and global commands. ```json { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/command-line.schema.json", "commands": [ { "commandKind": "bulk", "name": "build", "summary": "Build projects", "enableParallelism": true }, { "commandKind": "bulk", "name": "test", "summary": "Test projects", "enableParallelism": true }, { "commandKind": "global", "name": "clean", "summary": "Clean build outputs", "shellCommand": "node common/scripts/clean.js" } ], "parameters": [ { "parameterKind": "flag", "longName": "--production", "shortName": "-p", "description": "Production mode" } ] } ``` -------------------------------- ### Example Usage of rush litewatch Source: https://github.com/microsoft/rushstack/blob/main/rush-plugins/rush-litewatch-plugin/README.md This command demonstrates how to invoke the litewatch plugin to monitor multiple specified projects. ```bash $ rush litewatch --project p1 --project p2 ``` -------------------------------- ### Example Rig Package Structure Source: https://github.com/microsoft/rushstack/blob/main/libraries/rig-package/README.md Shows the structure of a 'rig package' containing shared configuration profiles. ```plaintext example-rig/package.json example-rig/profile/node-library/config/api-extractor.json example-rig/profile/web-library/config/api-extractor.json project1/package.json project1/config/api-extractor.json project1/config/other-tool2.json project1/config/other-tool3.json project1/src/index.ts project2/package.json project2/config/api-extractor.json project2/config/other-tool2.json project2/config/other-tool3.json project2/src/index.ts project3/package.json project3/config/api-extractor.json project3/config/other-tool2.json project3/config/other-tool3.json project3/src/index.ts ``` -------------------------------- ### Install @rushstack/eslint-config Source: https://github.com/microsoft/rushstack/blob/main/eslint/eslint-config/README.md Install the necessary ESLint and TypeScript packages along with the @rushstack/eslint-config package. ```sh cd your-project-folder npm install --save-dev eslint npm install --save-dev typescript npm install --save-dev @rushstack/eslint-config ``` -------------------------------- ### Help Output for Widget Tool Source: https://github.com/microsoft/rushstack/blob/main/libraries/ts-command-line/README.md Example of the auto-generated help documentation for the main tool when invoked with --help. ```text usage: widget [-h] [-v] ... The "widget" tool is a code sample for using the @rushstack/ts-command-line library. Positional arguments: push Pushes a widget to the service Optional arguments: -h, --help Show this help message and exit. -v, --verbose Show extra logging detail For detailed help about a specific command, use: widget -h ``` -------------------------------- ### Build and Start Serverless Stack Project with Heft Source: https://github.com/microsoft/rushstack/blob/main/build-tests-samples/heft-serverless-stack-tutorial/README.md Use the `--sst` flag with Heft commands to build and start your serverless stack project. This enables the serverless stack plugin for deployment and local development. ```shell # Build the project $ heft build --sst # Deploy the stub lambda and launch the local development client $ heft start --sst ``` -------------------------------- ### Install Rundown Globally Source: https://github.com/microsoft/rushstack/blob/main/apps/rundown/README.md Installs the rundown tool globally for command-line use. Use this for general analysis outside of a specific project build. ```shell npm install --global @rushstack/rundown ``` ```shell rundown --help ``` -------------------------------- ### Invoke Rush Serve Plugin Source: https://github.com/microsoft/rushstack/blob/main/rush-plugins/rush-serve-plugin/README.md This command initiates the rush-serve-plugin, which scans for configuration files and starts a development server. ```bash # The user invokes this command $ rush start ``` -------------------------------- ### ExampleB Class Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/spanSorting/api-extractor-scenarios.api.md Represents an example class with a method to try loading from a file. ```APIDOC ## Class ExampleB ### Description This class provides a method to attempt loading data from a file, with an option to enable an approved packages policy. ### Methods - **tryLoadFromFile**(approvedPackagesPolicyEnabled: boolean): boolean - Attempts to load from a file. Returns true if successful, false otherwise. ``` -------------------------------- ### CSS Module Example Source: https://github.com/microsoft/rushstack/blob/main/heft-plugins/heft-sass-plugin/README.md Example of a SCSS file structured as a CSS module. It defines class names and exports values. ```scss // src/Button.module.scss .root { background: blue; } .label { font-size: 14px; } :export { brandColor: #0078d4; } ``` -------------------------------- ### Build a CLI Tool with ts-command-line Source: https://context7.com/microsoft/rushstack/llms.txt Example demonstrating how to build a structured command-line interface using the ts-command-line framework, including actions, parameters, and execution logic. ```typescript import { CommandLineParser, CommandLineAction, type CommandLineFlagParameter, type CommandLineChoiceParameter, type CommandLineStringParameter } from '@rushstack/ts-command-line'; // Define an action (sub-command) class DeployAction extends CommandLineAction { private _force!: CommandLineFlagParameter; private _env!: CommandLineChoiceParameter; private _outputDir!: CommandLineStringParameter; public constructor() { super({ actionName: 'deploy', summary: 'Deploy the project to a target environment', documentation: 'Packages and deploys the built artifacts to staging or production.' }); } protected override onDefineParameters(): void { this._force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: '-f', description: 'Overwrite existing deployment without confirmation' }); this._env = this.defineChoiceParameter({ parameterLongName: '--env', description: 'Target environment for deployment', alternatives: ['staging', 'production'], environmentVariable: 'DEPLOY_ENV', defaultValue: 'staging' }); this._outputDir = this.defineStringParameter({ parameterLongName: '--output-dir', argumentName: 'FOLDER', description: 'Path to the compiled output folder', defaultValue: './dist' }); } protected override async onExecuteAsync(): Promise { console.log(`Deploying to: ${this._env.value}`); console.log(`Output dir: ${this._outputDir.value}`); console.log(`Force: ${this._force.value}`); // business logic here... } } // Define the top-level parser class MyCLI extends CommandLineParser { private _verbose!: CommandLineFlagParameter; public constructor() { super({ toolFilename: 'my-tool', toolDescription: 'A deployment tool for our monorepo projects.' }); this.addAction(new DeployAction()); } protected override onDefineParameters(): void { this._verbose = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', description: 'Enable verbose output' }); } protected override async onExecuteAsync(): Promise { if (this._verbose.value) console.log('[verbose mode on]'); await super.onExecuteAsync(); } } // Entry point const cli = new MyCLI(); cli.executeAsync().catch(console.error); // Usage: my-tool deploy --env production --force // Help: my-tool --help // Help: my-tool deploy --help ``` -------------------------------- ### Combined Build Flags Example Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/build-system.md Demonstrates combining `--from` and `--only` flags to build downstream dependents while specifically rebuilding only the 'utils' project. ```bash rush build --from utils --only utils ``` -------------------------------- ### Install Latest Rush Version Source: https://github.com/microsoft/rushstack/wiki/Contributing-to-this-repo Ensures you have the latest release of the Rush tool installed globally. This is a prerequisite for building Rushstack projects. ```bash C:\>npm install -g @microsoft/rush ``` -------------------------------- ### JavaScript Shim Examples Source: https://github.com/microsoft/rushstack/blob/main/heft-plugins/heft-sass-plugin/README.md Examples of generated JavaScript shims for CSS modules and global stylesheets, supporting different module formats. ```javascript // ESM shim (shimModuleFormat: "esnext") export { default } from "./Button.module.css"; ``` ```javascript // CommonJS shim (shimModuleFormat: "commonjs") module.exports = require("./Button.module.css"); module.exports.default = module.exports; ``` ```javascript // ESM shim import "./global.global.css"; export {}; ``` ```javascript // CommonJS shim require("./global.global.css"); ``` -------------------------------- ### Rush.json Example Configuration Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/project-configuration.md Defines the overall Rush configuration, including Rush and PNPM versions, project structure, and supported Node.js versions. ```json { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/rush.schema.json", "rushVersion": "5.109.0", "pnpmVersion": "8.15.0", "projectFolderMinDepth": 2, "projectFolderMaxDepth": 2, "nodeSupportedVersionRange": ">=18.17.0 <19.0.0", "projects": [ { "packageName": "@my-scope/my-app", "projectFolder": "apps/my-app", "shouldPublish": true, "subspaceName": "default" }, { "packageName": "@my-scope/my-lib", "projectFolder": "libraries/my-lib", "shouldPublish": true, "subspaceName": "default" } ] } ``` -------------------------------- ### ExampleA Class Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/spanSorting/api-extractor-scenarios.api.md Represents an example class with public members. ```APIDOC ## Class ExampleA ### Description This class is an example with public members, including a string property and a promise-returning method. ### Members - **member1**: string - (undocumented) - **member2**(): Promise - (undocumented) ``` -------------------------------- ### Install Global NPM Packages Source: https://github.com/microsoft/rushstack/wiki/Contributing-to-this-repo Installs or updates essential global packages required for development, including Rush itself. May require an administrator command prompt. ```bash C:\>npm install -g npm <-- optional, may require admin command prompt C:\>npm install -g pnpm C:\>npm install -g gulp C:\>npm install -g @microsoft/rush ``` -------------------------------- ### Webpack Configuration with Options Source: https://github.com/microsoft/rushstack/blob/main/webpack/loader-load-themed-styles/README.md Shows an example Webpack configuration using @microsoft/loader-load-themed-styles with specific options, alongside other loaders like css-loader, postcss-loader, and sass-loader. ```javascript use: [ { loader: "@microsoft/loader-load-themed-styles", // creates style nodes from JS strings options: { async: false } }, { loader: "css-loader", // translates CSS into CommonJS options: { modules: true, importLoaders: 2, localIdentName: '[name]_[local]_[hash:base64:5]', minimize: false } }, { loader: 'postcss-loader', options: { plugins: function () { return [ require('autoprefixer') ]; } } }, { loader: "sass-loader", } ] ``` -------------------------------- ### License File Name Type Examples Source: https://github.com/microsoft/rushstack/blob/main/webpack/webpack-embedded-dependencies-plugin/README.md Examples of valid license file names adhering to the 'LicenseFileName' type, which requires specific extensions. ```typescript const licenseFileName: LicenseFileName = 'custom-license-file-name.html'; const licenseMarkdownFileName: LicenseFileName = 'custom-license-file-name.md'; const licenseTextFileName: LicenseFileName = 'custom-license-file-name.txt'; ``` -------------------------------- ### Get Rush Command-Line Help Source: https://github.com/microsoft/rushstack/blob/main/apps/rush/README.md Display command-line help for Rush to understand available commands and options. This is useful for exploring Rush's capabilities. ```bash $ rush -h ``` -------------------------------- ### Basic Rush SDK Usage Source: https://context7.com/microsoft/rushstack/llms.txt Load Rush configuration and access project details. Ensure Rush is installed in your environment. ```typescript import { RushConfiguration } from '@rushstack/rush-sdk'; const config = RushConfiguration.loadFromDefaultLocation(); console.log('Common folder:', config.commonFolder); console.log('Rush version:', config.rushVersion); // List all projects in the monorepo for (const project of config.projects) { console.log(`${project.packageName} -> ${project.projectRelativeFolder}`); } ``` -------------------------------- ### Run Playwright Tunnel as Browser Host Source: https://github.com/microsoft/rushstack/blob/main/apps/playwright-browser-tunnel/README.md Instantiate and start `PlaywrightTunnel` in the environment where the browser process should run. This example configures the tunnel to wait for an incoming connection on a specific port and sets up a temporary directory for Playwright core installation. ```typescript import { ConsoleTerminalProvider, Terminal, TerminalProviderSeverity } from '@rushstack/terminal'; import { PlaywrightTunnel } from '@rushstack/playwright-browser-tunnel'; import path from 'node:path'; import os from 'node:os'; const terminalProvider = new ConsoleTerminalProvider(); const terminal = new Terminal(terminalProvider); const tunnel = new PlaywrightTunnel({ mode: 'wait-for-incoming-connection', listenPort: 56767, tmpPath: path.join(os.tmpdir(), 'playwright-browser-tunnel'), terminal, onStatusChange: (status) => terminal.writeLine(`status: ${status}`) }); await tunnel.startAsync({ keepRunning: true }); ``` -------------------------------- ### ExampleC Class Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/spanSorting/api-extractor-scenarios.api.md Represents an undocumented example class with a public method. ```APIDOC ## Class ExampleC ### Description This is an undocumented public class with a single public method. ### Methods - **member1**(): void - (undocumented) ``` -------------------------------- ### exampleFunction Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-documenter-test/etc/api-documenter-test.api.md An example function that takes an ExampleTypeAlias and a number, returning an IDocInterface1. ```APIDOC ## exampleFunction(x: ExampleTypeAlias, y: number): IDocInterface1 ### Description An example function that takes an ExampleTypeAlias and a number, returning an IDocInterface1. ``` -------------------------------- ### ESLint Configuration for Packlets (Basic) Source: https://github.com/microsoft/rushstack/blob/main/eslint/eslint-plugin-packlets/README.md Shows how to integrate the `@rushstack/eslint-plugin-packlets` into a basic `typescript-eslint` setup by extending the recommended rules. ```javascript module.exports = { root: true, parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@rushstack/eslint-plugin-packlets/recommended' // <--- ADD THIS ], parserOptions: { project: './tsconfig.json', sourceType: 'module', tsconfigRootDir: __dirname } }; ``` -------------------------------- ### Minimal Rush Monorepo Configuration Source: https://context7.com/microsoft/rushstack/llms.txt Example of a minimal `rush.json` file defining the monorepo structure, Rush version, and projects. ```json { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/rush.schema.json", "rushVersion": "5.175.1", "pnpmVersion": "10.27.0", "nodeSupportedVersionRange": ">=18.0.0 <23.0.0", "projects": [ { "packageName": "@my-org/my-library", "projectFolder": "libraries/my-library" }, { "packageName": "@my-org/my-app", "projectFolder": "apps/my-app" } ] } ``` -------------------------------- ### API Documenter CLI Command Source: https://context7.com/microsoft/rushstack/llms.txt Command to install API Documenter globally and generate Markdown documentation from `.api.json` files. ```bash # Install api-documenter npm install -g @microsoft/api-documenter # Generate Markdown documentation from .api.json files in ./input/ api-documenter markdown --input-folder ./input --output-folder ./docs/api ``` -------------------------------- ### Initial Subspace Setup Workflow Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/subspace.md Steps to set up subspaces, including creating configuration directories, enabling the feature, assigning projects, and running `rush update` to generate lock files. ```bash # 1. Create subspace configuration mkdir -p common/config/subspaces/team-a # 2. Enable subspaces in subspaces.json # Edit: common/config/rush/subspaces.json # 3. Assign projects in rush.json # Edit: rush.json - add subspaceName to projects # 4. Run update to generate lock files rush update ``` -------------------------------- ### Rush install vs update behavior Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/SKILL.md Use `rush update` after cloning, git pull, or modifying package.json to update shrinkwrap and install new dependencies. Use `rush install` for read-only installs from existing shrinkwrap in CI/CD pipelines to ensure version consistency. ```bash rush update ``` ```bash rush install ``` -------------------------------- ### API Extractor Configuration Example Source: https://context7.com/microsoft/rushstack/llms.txt A typical `config/api-extractor.json` file. Configure entry points, API reports, doc models, and d.ts rollups. ```json { "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", "mainEntryPointFilePath": "/lib/index.d.ts", "bundledPackages": [], "apiReport": { "enabled": true, "reportFolder": "/etc/" }, "docModel": { "enabled": true, "apiJsonFilePath": "/temp/.api.json" }, "dtsRollup": { "enabled": true, "untrimmedFilePath": "/dist/.d.ts", "publicTrimmedFilePath": "/dist/-public.d.ts" }, "tsdocMetadata": { "enabled": true }, "messages": { "extractorMessageReporting": { "ae-missing-release-tag": { "logLevel": "warning" } } } } ``` -------------------------------- ### Example output format Source: https://github.com/microsoft/rushstack/blob/main/rush-plugins/rush-published-versions-json-plugin/README.md The generated JSON file maps published package names to their current versions. Packages are included if they have 'shouldPublish' set to true or have a 'versionPolicy' assigned in rush.json. ```json { "@my-scope/my-library": "1.2.3", "@my-scope/my-app": "0.5.0" } ``` -------------------------------- ### Install @rushstack/eslint-patch Source: https://context7.com/microsoft/rushstack/llms.txt Install the @rushstack/eslint-patch package for ESLint monorepo enhancements and the global @rushstack/eslint-bulk tool. ```bash npm install --save-dev @rushstack/eslint-patch npm install --global @rushstack/eslint-bulk ``` -------------------------------- ### IEnvironmentConfigurationInitializeOptions Interface Source: https://github.com/microsoft/rushstack/blob/main/common/reviews/api/rush-lib.api.md Options for initializing environment configuration. ```APIDOC ## Interface: IEnvironmentConfigurationInitializeOptions ### Description Options that can be provided when initializing environment configuration. ### Properties - `doNotNormalizePaths? (boolean)`: If true, paths will not be normalized. ``` -------------------------------- ### Build Project and Dependencies with --to Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/build-system.md Use the `--to` flag to build a specific project along with all of its dependencies. This is useful when building an application for testing or publishing a package. ```bash rush build --to @my-scope/my-app ``` -------------------------------- ### Install and Build Integration Test Code Source: https://github.com/microsoft/rushstack/blob/main/build-tests/rush-redis-cobuild-plugin-integration-test/README.md Installs dependencies and builds the integration test project for the rush-redis-cobuild-plugin. ```sh rush update rush build -t rush-redis-cobuild-plugin-integration-test ``` -------------------------------- ### Initialize Rush Cloud Credentials Source: https://github.com/microsoft/rushstack/blob/main/rush-plugins/rush-http-build-cache-plugin/README.md Use this command to interactively set up credentials for Rush's cloud build cache. ```console rush update-cloud-credentials --interactive ``` -------------------------------- ### Incorrect vs. Correct Dependency Management Commands Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/dependency-management.md Demonstrates the correct way to add dependencies using 'rush add' instead of direct package manager commands like 'npm install' or 'pnpm add'. ```bash # Incorrect: npm install lodash pnpm add typescript # Correct: rush add -p lodash rush add -p typescript ``` -------------------------------- ### Plugin Accessor API Example Source: https://github.com/microsoft/rushstack/blob/main/heft-plugins/heft-sass-plugin/README.md Example of how to access the `ISassPluginAccessor` in another Heft plugin to hook into the Sass compilation pipeline. ```typescript import { ISassPluginAccessor } from '@rushstack/heft-sass-plugin'; // In your plugin's apply() method: const sassAccessor = session.requestAccessToPlugin< ISassPluginAccessor >( '@rushstack/heft-sass-plugin', 'sass-plugin', '@rushstack/heft-sass-plugin' ); sassAccessor.hooks.postProcessCss.tapPromise('my-plugin', async (css, filePath) => { // Transform CSS after Sass compilation but before it is written to cssOutputFolders return transformedCss; }); ``` -------------------------------- ### Case 3: Parallel Cobuilds Setup Source: https://github.com/microsoft/rushstack/blob/main/build-tests/rush-redis-cobuild-plugin-integration-test/README.md Steps to set up and run two cobuild commands in parallel. This requires Visual Studio Code and involves clearing the Redis server and build cache before initiating the tasks. ```sh # Under rushstack/build-tests/rush-redis-cobuild-plugin-integration-test docker compose down && docker compose up -d ``` ```sh # Under rushstack/build-tests/rush-redis-cobuild-plugin-integration-test/sandbox/repo rm -rf common/temp/build-cache ``` -------------------------------- ### License File Generator Type Example Source: https://github.com/microsoft/rushstack/blob/main/webpack/webpack-embedded-dependencies-plugin/README.md An example demonstrating how to define and use the 'LicenseFileGeneratorFunction' type for custom license file generation. ```typescript const licenseFileGenerator: LicenseFileGeneratorFunction = (packages: IPackageData[]): string => { return packages .map((pkg) => { return `

${pkg.name}

${pkg.license}

`; }).join(''); } ``` -------------------------------- ### Install Rundown as a Dev Dependency Source: https://github.com/microsoft/rushstack/blob/main/apps/rundown/README.md Installs rundown as a development dependency within a project. Recommended for integrating snapshot generation into your build process. ```shell cd my-tool npm install @rushstack/rundown --save-dev ``` -------------------------------- ### Get Package Dependencies Hash Source: https://github.com/microsoft/rushstack/blob/main/libraries/package-deps-hash/README.md Use this to get the current dependencies hash for the working directory. Compare this with an existing hash to determine if a rebuild is necessary. ```typescript let _ = require('lodash'); let { getPackageDeps } = require('@rushstack/package-deps-hash'); // Gets the current deps object for the current working directory let deps = getPackageDeps(); let existingDeps = JSON.parse(fs.readFileSync('package-deps.json')); if (_.isEqual(deps, existingDeps)) { // Skip re-building package. } else { // Rebuild package. } ``` -------------------------------- ### Basic rush.json Structure Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/project-configuration.md Sets up core Rush configuration including versioning, package manager, project folder depth, and Node.js version. ```json { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/rush.schema.json", "rushVersion": "5.x.x", // Package Manager Selection (choose one) "pnpmVersion": "8.x.x", // "npmVersion": "8.x.x", // "yarnVersion": "1.x.x", // Project Folder Depth "projectFolderMinDepth": 2, "projectFolderMaxDepth": 2, // Node.js Version Requirement "nodeSupportedVersionRange": ">=14.15.0", // Projects Array "projects": [] } ``` -------------------------------- ### Update Dependencies with rush update Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/core-commands.md Installs and updates dependencies, regenerating the shrinkwrap file. Use the --purge flag for a clean installation or --to to specify a project and its dependencies. ```bash rush update # Standard update rush update --purge # Clean then update rush update --to @my/app # Update specific project and deps ``` -------------------------------- ### Use Incremental Builds for Development Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/build-system.md Prefer 'rush build' over 'rush rebuild' during development to leverage incremental builds and speed up the development cycle. ```bash # Always rebuild everything rush rebuild # Incremental build for development rush build ``` -------------------------------- ### Start Redis Instance for Cobuilds Source: https://github.com/microsoft/rushstack/blob/main/build-tests/rush-redis-cobuild-plugin-integration-test/README.md Stop any existing Redis Docker containers and then start a new one in detached mode. This ensures a clean Redis environment for the cobuild test. ```bash docker compose down && docker compose up -d ``` -------------------------------- ### Preserve Dynamic Require Example Source: https://github.com/microsoft/rushstack/blob/main/webpack/preserve-dynamic-require-plugin/README.md This example shows how a dynamic `require` call is preserved by the plugin. The emitted bundle will retain the `require(path)` call instead of attempting to resolve it during the build. ```javascript function requireSomeUserThing(path) { return require(path); } ``` -------------------------------- ### Resolve Workspace Linking Issues with Rush Install Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/dependency-management.md If local changes are not reflected, try `rush install` to reinstall dependencies and recreate symlinks. Verify links using `ls -la node_modules/@my-scope/`. ```bash # Reinstall to recreate links rush install ``` ```bash # Check links are correct ls -la node_modules/@my-scope/ ``` -------------------------------- ### Start Tunneled Browser Connection Source: https://github.com/microsoft/rushstack/blob/main/apps/playwright-browser-tunnel/README.md Use `tunneledBrowserConnection()` in your test environment to start a remote WebSocket server and a local WebSocket endpoint. This allows your Playwright client to connect to a browser instance managed by the tunnel. ```typescript import { tunneledBrowserConnection } from '@rushstack/playwright-browser-tunnel'; import playwright from 'playwright-core'; using connection = await tunneledBrowserConnection(); // Build the connect URL with query parameters consumed by the local proxy. const url = new URL(connection.remoteEndpoint); url.searchParams.set('browser', 'chromium'); url.searchParams.set('launchOptions', JSON.stringify({ headless: true })); const browser = await playwright.chromium.connect(url.toString()); // ...run tests... await browser.close(); ``` -------------------------------- ### Build specific project and its dependencies with --to Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/SKILL.md Use the `--to` flag to select a specific project and all of its dependencies for a command. This ensures that the entire dependency chain is processed. ```bash rush build --to @my-company/my-project ``` ```bash rush build --to my-project # If project name is unique ``` ```bash rush build --to . # Use current directory's project ``` -------------------------------- ### Check for Playwright Local Browser Server Extension Installation Source: https://github.com/microsoft/rushstack/blob/main/apps/playwright-browser-tunnel/README.md Use `isExtensionInstalledAsync()` to detect if the Playwright Local Browser Server VS Code extension is installed and active in the current environment. This is useful for conditionally skipping local-browser-only scenarios. ```typescript import { isExtensionInstalledAsync } from '@rushstack/playwright-browser-tunnel'; if (!(await isExtensionInstalledAsync())) { throw new Error('Playwright Local Browser Server extension is not installed/active in this environment'); } ``` -------------------------------- ### Recommended package.json Build Scripts Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/build-system.md Set up 'package.json' scripts to call Heft commands for building, cleaning, and testing. This provides a consistent interface for project tasks. ```json { "scripts": { "build": "heft build", "build:production": "heft build --production", "clean": "heft clean", "test": "heft test" } } ``` -------------------------------- ### Build Project and Dependents with --from Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/references/build-system.md Use the `--from` flag to build a project and all of its downstream dependents. This is useful after library changes to test the impact on other projects. ```bash rush build --from @my-scope/utils ``` -------------------------------- ### Readonly Variables Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/readonlyDeclarations/api-extractor-scenarios.api.md Shows examples of readonly variables and constants. ```APIDOC ## Constants and Variables ### Description Documentation for top-level readonly variables and constants. ### Members - **READONLY_VARIABLE**: string (constant) - Description: A constant string value. - Value: "Hello world!" - **TSDOC_READONLY_VARIABLE**: string (variable) - Description: A variable that is intended to be readonly. ``` -------------------------------- ### Example Token Handler Script for Basic Auth Source: https://github.com/microsoft/rushstack/blob/main/rush-plugins/rush-http-build-cache-plugin/README.md A JavaScript script to generate a Basic Authorization header for authenticating with the build cache server. It reads user and token from environment variables. ```javascript // common/scripts/build-cache-auth.js const credentials = `${process.env.CACHE_USER}:${process.env.CACHE_TOKEN}`; console.log('Basic ' + Buffer.from(credentials).toString('base64')); ``` -------------------------------- ### EcmaSymbols Namespace Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-documenter-test/etc/api-documenter-test.api.md Namespace containing an example unique symbol. ```APIDOC ## EcmaSymbols ### Description Namespace containing an example unique symbol. ### Symbols #### example: unique symbol ``` -------------------------------- ### exampleD Function Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/spanSorting/api-extractor-scenarios.api.md A public constant representing a function with an object parameter. ```APIDOC ## Function exampleD ### Description This is a public constant that exports a function. The function accepts a single object parameter with a string property and a function. ### Parameters - **o**: object - Required - An object containing: - **a**: number - (undocumented) - **b**(): string - (undocumented) ``` -------------------------------- ### IHeftTaskStartHookOptions Source: https://github.com/microsoft/rushstack/blob/main/common/reviews/api/heft.api.md Options provided to the hook that runs when a Heft task starts. ```APIDOC ## interface IHeftTaskStartHookOptions ### Description Options provided to the hook that runs when a Heft task starts. ### Properties * operation (Operation) - Represents the operation metadata for the task start. ``` -------------------------------- ### Add Plugin DevDependency Source: https://github.com/microsoft/rushstack/blob/main/heft-plugins/heft-static-asset-typings-plugin/README.md Install the plugin as a dev dependency using rush. ```bash rush add -p @rushstack/heft-static-asset-typings-plugin --dev ``` -------------------------------- ### Select Package Manager in rush.json Source: https://github.com/microsoft/rushstack/blob/main/skills/rushstack-best-practices/SKILL.md Configure the preferred package manager (pnpm, npm, or yarn) by specifying its version in the rush.json file. pnpm is the recommended option for efficiency and strictness. ```json { "pnpmVersion": "8.x.x" // Preferred - efficient, strict // "npmVersion": "8.x.x" // Alternative // "yarnVersion": "1.x.x" // Alternative } ``` -------------------------------- ### Install ESLint Patch Dependency Source: https://github.com/microsoft/rushstack/blob/main/eslint/eslint-patch/README.md Add @rushstack/eslint-patch as a development dependency to your project. ```bash cd your-project npm install --save-dev @rushstack/eslint-patch ``` -------------------------------- ### Build and Run Rush Integration Tests Source: https://github.com/microsoft/rushstack/blob/main/build-tests/rush-package-manager-integration-test/README.md Commands to build the test project and execute all tests. Ensure Rush and the test project are built before running tests. ```bash # Build the test project first cd build-tests/rush-package-manager-integration-test rush build # Run all tests npm run test ``` ```bash rush build --to rush-package-manager-integration-test cd build-tests/rush-package-manager-integration-test npm run test ``` -------------------------------- ### Reexported Class Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-test-01/etc/api-extractor-test-01.api.md A class that is re-exported from another module, providing a method to get its own reference. ```typescript export class ReexportedClass { // (undocumented) getSelfReference(): ReexportedClass; // (undocumented) getValue(): string; } ``` -------------------------------- ### Add Plugin to Heft Project Source: https://github.com/microsoft/rushstack/blob/main/heft-plugins/heft-json-schema-typings-plugin/README.md Install the plugin as a dev dependency using rush add. ```bash rush add -p @rushstack/heft-json-schema-typings-plugin --dev ``` -------------------------------- ### Define and Execute Dynamic Command Line Source: https://github.com/microsoft/rushstack/blob/main/libraries/ts-command-line/README.md Use DynamicCommandLineParser and DynamicCommandLineAction for runtime discovery of commands and parameters. This example demonstrates defining a parser, adding a flag parameter, defining an action with its own parameters, and executing the parser. ```typescript const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({ toolFilename: 'widget', toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.' }); commandLineParser.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', description: 'Show extra logging detail' }); const action: DynamicCommandLineAction = new DynamicCommandLineAction({ actionName: 'push', summary: 'Pushes a widget to the service', documentation: 'Here we provide a longer description of how our action works.' }); commandLineParser.addAction(action); action.defineFlagParameter({ parameterLongName: '--force', parameterShortName: '-f', description: 'Push and overwrite any existing state' }); action.defineChoiceParameter({ parameterLongName: '--protocol', description: 'Specify the protocol to use', alternatives: ['ftp', 'webdav', 'scp'], environmentVariable: 'WIDGET_PROTOCOL', defaultValue: 'scp' }); commandLineParser.executeAsync().then(() => { console.log('The action is: ' + commandLineParser.selectedAction!.actionName); console.log('The force flag is: ' + action.getFlagParameter('--force').value); }); ``` -------------------------------- ### Class A Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/mixinPattern/api-extractor-scenarios.api.md Represents a class 'A' with an optional string property 'prop'. This is a basic example of a class structure. ```APIDOC ## Class A ### Description Represents a class 'A' with an optional string property 'prop'. ### Members #### Properties - **prop** (string) - Optional - An optional string property. ``` -------------------------------- ### Public Class Export Source: https://github.com/microsoft/rushstack/blob/main/build-tests/api-extractor-scenarios/etc/ecmaScriptPrivateFields/api-extractor-scenarios.api.md Defines a public class named 'Example'. This is a basic export declaration. ```typescript // @public (undocumented) export class Example { } ``` -------------------------------- ### IApiInitializerMixinOptions Source: https://github.com/microsoft/rushstack/blob/main/common/reviews/api/api-extractor-model.api.md Mixin options for an initializer, providing the token range for the initializer. ```APIDOC ## IApiInitializerMixinOptions ### Description Mixin options for an initializer. ### Properties - **initializerTokenRange** (IExcerptTokenRange) - The token range for the initializer. ``` -------------------------------- ### IExcerptTokenRange Interface Source: https://github.com/microsoft/rushstack/blob/main/common/reviews/api/api-extractor-model.api.md Defines a range within a sequence of tokens, specified by start and end indices. ```APIDOC ## Interface: IExcerptTokenRange ### Description Defines a range within a sequence of tokens, specified by start and end indices. ### Properties - **startIndex** (number) - The starting index of the token range. - **endIndex** (number) - The ending index of the token range. ``` -------------------------------- ### CustomTipsConfiguration Source: https://github.com/microsoft/rushstack/blob/main/common/reviews/api/rush-lib.api.md Handles custom tips and warnings displayed to the user within the Rush environment. Allows for the registration and display of custom tips based on predefined IDs and severities. ```APIDOC ## Class: CustomTipsConfiguration ### Description Manages custom tips and warnings for the Rush CLI. It allows for the display of specific tips based on their IDs and severity levels. ### Constructor * `constructor(configFilePath: string)` Initializes a new instance of the `CustomTipsConfiguration` class. ### Properties * `customTipRegistry: Readonly>` A registry of all available custom tip information. * `providedCustomTipsByTipId: ReadonlyMap` A map of custom tips provided by the configuration, keyed by their ID. ### Methods * `_showErrorTip(terminal: ITerminal, tipId: CustomTipId): void` (Internal) Displays an error tip to the terminal. * `_showInfoTip(terminal: ITerminal, tipId: CustomTipId): void` (Internal) Displays an informational tip to the terminal. * `_showTip(terminal: ITerminal, tipId: CustomTipId): void` (Internal) Displays a generic tip to the terminal. * `_showWarningTip(terminal: ITerminal, tipId: CustomTipId): void` (Internal) Displays a warning tip to the terminal. ```