### Yarn Install Output Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2023-10-23-release-4.0.mdx This snippet shows the improved output of 'yarn install', detailing added packages and their total weight, while reducing noise from peer dependency warnings. ```bash yarn install # Example output: # Success # Packages added: # - @babel/runtime@7.22.11 (10.5 MiB) # - react-scripts@5.0.1 (25.3 MiB) # Done in 1.50s ``` -------------------------------- ### Performance Benchmark Setup Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2023-10-23-release-4.0.mdx This command sets up a performance benchmark using hyperfine to compare Yarn versions by installing Gatsby and its dependencies from a cold cache. ```bash hyperfine -L v stable,canary --prepare 'rm -rf ~/.yarn/berry/cache' 'cd $(mktemp -d) && yarn init -2 && yarn set version {v} && yarn && yarn add gatsby --mode=skip-build' ``` -------------------------------- ### Start Development Server Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/README.md Starts a local development server for live previewing changes. Changes are reflected without server restart. ```bash yarn start ``` -------------------------------- ### Install @yarnpkg/pnpify Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-pnpify/README.md Install the pnpify CLI tool as a development dependency. ```bash yarn add -D @yarnpkg/pnpify ``` -------------------------------- ### Install Yarn from Source Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Install the latest Yarn build directly from the repository. This method does not use Corepack and stores the binary locally. ```bash yarn set version from sources ``` -------------------------------- ### Normalized Configuration Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-01-24-release-2.0.mdx Presents an example of the .yarnrc.yml file, highlighting the unified configuration system in Yarn 2. ```yaml initScope: yarnpkg npmPublishAccess: public yarnPath: scripts/run-yarn.js ``` -------------------------------- ### Install @yarnpkg/extensions Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-extensions/README.md Install the @yarnpkg/extensions package using Yarn. ```bash yarn add @yarnpkg/extensions ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/usage.mdx Run `yarn` to install project dependencies. This command is an alias for `yarn install`. ```bash yarn ``` -------------------------------- ### Install @yarnpkg/sdks Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-sdks/README.md Install the SDKs package as a development dependency using Yarn. ```bash yarn add -D @yarnpkg/sdks ``` -------------------------------- ### Update All Installed SDKs and Editor Settings Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/editor-sdks.mdx Run this command to update all installed SDKs and their corresponding editor settings. ```bash yarn dlx @yarnpkg/sdks ``` -------------------------------- ### Generate Hello World Package Files Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/protocols/exec.mdx Example of generating a simple 'hello-world' package by writing `package.json` and `index.js` to the build directory. ```typescript fs.writeFileSync(path.join(execEnv.buildDir, 'package.json'), JSON.stringify({ name: 'hello-world', version: '1.0.0', })); fs.writeFileSync(path.join(execEnv.buildDir, 'index.js'), " module.exports = 'hello world!'; "); ``` -------------------------------- ### Start Local Docusaurus Server Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/contributing.mdx Run this command to start a local development server for the Docusaurus documentation website. This allows you to preview your documentation changes in real-time. ```bash yarn start ``` -------------------------------- ### Initialize New Project with Yarn Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Initialize a new project with Yarn version 2 or higher. This command requires Corepack to be installed. ```bash yarn init -2 ``` -------------------------------- ### Yarn Config Command Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2023-10-23-release-4.0.mdx Demonstrates the new tree display and positional argument support for the 'yarn config' command, allowing focused viewing of specific settings. ```bash yarn config # Example output: # yarn config v3.6.4 # yarn config v4.0.0 # # # nodeLinker: "node-modules" # # ... other config settings # # Done in 1.50s ``` -------------------------------- ### Initialize a new library within a monorepo Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/recipes.mdx Start a new library in a monorepo by running the 'init' command in the target directory without manual folder creation. ```bash yarn packages/my-new-lib init ``` -------------------------------- ### Yarn Doctor Output Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/migrating/pnp.mdx Example output from the Yarn Doctor tool, highlighting issues like undeclared dependencies and unsafe references to node_modules. ```text ➤ YN0000: Found 1 package(s) to process ➤ YN0000: For a grand total of 236 file(s) to validate ➤ YN0000: ┌ /webpack-dev-server/package.json ➤ YN0000: │ /webpack-dev-server/test/testSequencer.js:5:19: Undeclared dependency on @jest/test-sequencer ➤ YN0000: │ /webpack-dev-server/client-src/default/webpack.config.js:12:14: Webpack configs from non-private packages should avoid referencing loaders without require.resolve ➤ YN0000: │ /webpack-dev-server/test/server/contentBase-option.test.js:68:8: Strings should avoid referencing the node_modules directory (prefer require.resolve) ➤ YN0000: └ Completed in 5.12s ➤ YN0000: Failed with errors in 5.12s ``` -------------------------------- ### Install Yarn Canary Build Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Use this command to install a Release Candidate build of Yarn, which may include features not yet available on the stable channel. ```bash yarn set version canary ``` -------------------------------- ### Correct module import usage Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-doctor/README.md This example shows the correct way to import a module by its name, which is compatible with Plug'n'Play. This is the preferred method over referencing 'node_modules' directly. ```javascript var foo = require("lodash"); // importing a module by its name ``` -------------------------------- ### Install Git Workspace with Tag Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/protocols/git.mdx Clone a Git repository and install a specific workspace, pinning it to a tag. Requires the remote repository to use Yarn or npm (v7+). ```bash git@github.com:yarnpkg/berry.git#workspace=@yarnpkg/shell&tag=@yarnpkg/shell/2.1.0 ``` -------------------------------- ### Install Corepack Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Install Corepack globally using npm. This tool manages package manager versions. ```bash npm install -g corepack ``` -------------------------------- ### Install Yarn from Specific Source Branch Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Install a specific version of Yarn from a particular branch or pull request in the repository. This is useful for testing. ```bash yarn set version from sources --branch 1211 ``` -------------------------------- ### Integrate Corepack with Volta Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/corepack.mdx Installs Corepack globally and enables it with a specific install directory to ensure it overwrites Volta's Yarn shims, forcing integration. ```bash npm install -g corepack # Specifying an explicit install-directory makes corepack overwrite volta's yarn shims, which is what we want corepack enable --install-directory "~/.volta/bin" ``` -------------------------------- ### Virtual Folder Path Examples Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.mdx Illustrates the transformation of virtual folder paths to their concrete file paths. The '__virtual__//' segment is processed to derive the final path. ```text /path/to/some/folder/__virtual__/a0b1c2d3/0/subpath/to/file.dat /path/to/some/folder/subpath/to/file.dat ``` ```text /path/to/some/folder/__virtual__/e4f5a0b1/0/subpath/to/file.dat /path/to/some/folder/subpath/to/file.dat (different hash, same result) ``` ```text /path/to/some/folder/__virtual__/a0b1c2d3/1/subpath/to/file.dat /path/to/some/subpath/to/file.dat ``` ```text /path/to/some/folder/__virtual__/a0b1c2d3/3/subpath/to/file.dat /path/subpath/to/file.dat ``` -------------------------------- ### Clone Monorepo, Build, and Pack Workspace Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/protocols/exec.mdx Demonstrates cloning a git repository, installing its dependencies, packing a specific workspace, and extracting its contents to the build directory. ```typescript const pathToRepo = path.join(execEnv.tempDir, 'repo'); const pathToArchive = path.join(execEnv.tempDir, 'archive.tgz'); const pathToSubpackage = path.join(pathToRepo, 'packages/foobar'); // Clone the repository child_process.execFileSync(`git`, [`clone`, `git@github.com:foo/bar`, pathToRepo]); // Install the dependencies child_process.execFileSync(`yarn`, [`install`], {cwd: pathToRepo}); // Pack a specific workspace child_process.execFileSync(`yarn`, [`pack`, `--out`, pathToArchive], {cwd: pathToSubpackage}); // Send the package content into the build directory child_process.execFileSync(`tar`, [`-x`, `-z`, `--strip-components=1`, `-f`, pathToArchive, `-C`, execEnv.buildDir]); ``` -------------------------------- ### Example of instantiating WorkspaceCwd in Prolog Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/error-codes.mdx Demonstrates how to correctly instantiate the WorkspaceCwd parameter before using it in a predicate like workspace_field. This prevents Prolog instantiation errors. ```prolog workspace_field(WorkspaceCwd, 'name', _). ``` ```prolog workspace(WorkspaceCwd), workspace_field(WorkspaceCwd, 'name', _). ``` -------------------------------- ### Calling Binaries with yarn run bin Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/migrating/pnp.mdx Instead of relying on `node_modules/.bin`, use `yarn run bin` or its shortcut `yarn` to execute binaries. This command works seamlessly with PnP installations. ```bash yarn run jest ``` ```bash # or, using the shortcut: yarn jest ``` -------------------------------- ### Install Dependencies and Pick Up Source Changes Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/contributing.mdx Run this command within the Yarn repository to install dependencies. It automatically picks up changes made to the TypeScript sources without requiring a separate build step. ```bash yarn install # Will automatically pick up any changes you made to sources ``` -------------------------------- ### Check Corepack Status Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/corepack.mdx Verifies if Corepack is enabled and correctly installed by checking for the COREPACK_ROOT environment variable. A path output indicates successful installation. ```bash yarn exec env | grep COREPACK_ROOT ``` -------------------------------- ### New Lockfile Format Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-01-24-release-2.0.mdx Illustrates the new pure YAML format for Yarn 2's lockfile and configuration files, replacing the older custom format. ```yaml "@yarnpkg/parsers@workspace:^2.0.0-rc.6, @yarnpkg/parsers@workspace:packages/yarnpkg-parsers": version: 0.0.0-use.local resolution: "@yarnpkg/parsers@workspace:packages/yarnpkg-parsers" dependencies: js-yaml: ^3.10.0 pegjs: ^0.10.0 languageName: unknown linkType: soft ``` -------------------------------- ### Use 'pnpm' Node Linker Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2021-09-25-release-3.1.mdx Switch to a symlink-based installation strategy by setting 'nodeLinker' to 'pnpm' in your .yarnrc.yml. This mimics the installation method used by the pnpm package manager. ```yaml nodeLinker: pnpm ``` -------------------------------- ### Configure Supported Architectures for Conditional Packages Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2021-09-25-release-3.1.mdx Manually define the operating systems and CPU architectures for which packages should be fetched and installed. This is particularly useful for zero-install scenarios requiring a strict set of supported environments. ```yaml supportedArchitectures: os: [linux, darwin] cpu: [x64, arm64] ``` -------------------------------- ### Add PnPify Dependency Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnpify.mdx Install PnPify as a project dependency using Yarn. ```bash yarn add @yarnpkg/pnpify ``` -------------------------------- ### Yarn Workspaces Focus Command Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-07-09-release-2.1.mdx The `yarn workspaces focus` command installs dependencies for a specific workspace and its direct dependencies. This is useful for reducing install size, especially when integrating monorepos with Docker images using the `--production` flag. ```bash yarn workspaces focus ``` ```bash yarn workspaces focus --production ``` -------------------------------- ### Explain Peer Dependencies Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/error-codes.mdx Use this command to get detailed information about peer dependency resolution issues. Pass the 'p'-prefixed code from the original error message to this command. ```bash yarn explain peer-requirements pf649c ``` -------------------------------- ### Normalized Shell Scripts Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-01-24-release-2.0.mdx Demonstrates how Yarn 2's shell interpreter handles script fields, ensuring compatibility across different operating systems. ```json { "scripts": { "redirect": "node ./something.js > hello.md", "no-cross-env": "NODE_ENV=prod webpack" } } ``` -------------------------------- ### Add TypeScript and enable VSCode integration Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/recipes.mdx Install TypeScript as a development dependency and enable VSCode integration for enhanced developer experience. ```bash yarn add --dev typescript yarn dlx @yarnpkg/sdks vscode ``` -------------------------------- ### Build Dependency Tracking Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-01-24-release-2.0.mdx This log output shows Yarn 2's build dependency tracking in action, indicating that the 'sharp' package needed to be rebuilt because its dependency tree changed. ```bash ➤ YN0000: ┌ Link step ➤ YN0007: │ sharp@npm:0.23.0 must be rebuilt because its dependency tree changed ➤ YN0000: └ Completed in 16.92s ➤ YN0000: Done with warnings in 21.07s ``` -------------------------------- ### Accessing Files with @yarnpkg/fslib Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx Use @yarnpkg/fslib to access files, including those within zip archives. This example demonstrates setting up PosixFS and ZipOpenFS for cross-platform compatibility. ```ts const {PosixFS, ZipOpenFS} = require(`@yarnpkg/fslib`); const libzip = require(`@yarnpkg/libzip`).getLibzipSync(); // This will transparently open zip archives const zipOpenFs = new ZipOpenFS({libzip}); // This will convert all paths into a Posix variant, required for cross-platform compatibility const crossFs = new PosixFS(zipOpenFs); console.log(crossFs.readFileSync(`C:\\path\\to\\archive.zip\\package.json`)); ``` -------------------------------- ### Generator Script for Exec Protocol Source: https://github.com/yarnpkg/berry/blob/master/packages/plugin-exec/README.md Example Node.js script used with the `exec:` protocol. It populates the `buildDir` with `package.json` and `index.js` files using the provided `execEnv` global. ```javascript const {buildDir} = execEnv; fs.writeFileSync(path.join(buildDir, `package.json`), JSON.stringify({ name: `pkg`, version: `1.0.0`, })); fs.writeFileSync(path.join(buildDir, `index.js`), `module.exports = ${Date.now()}; `); ``` -------------------------------- ### Configuring Yarn Cache Folder via CLI (Deprecated) Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/error-codes.mdx This example shows a deprecated way of passing CLI options like `--cache-folder`. Yarn v2+ consolidates configuration in `.yarnrc.yml` files. ```bash yarn install --cache-folder .yarn ``` -------------------------------- ### Performance Benchmark Results Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2023-10-23-release-4.0.mdx Shows the benchmark results comparing Yarn 3.6.0 and Yarn 4.0.0 for installing Gatsby, highlighting a 3.92x speed improvement with Yarn 4.0.0. ```js Benchmark 1: 3.6.0 Time (mean ± σ): 65.599 s ± 2.214 s [User: 82.952 s, System: 8.638 s] Range (min … max): 62.167 s … 68.277 s 10 runs Benchmark 2: 4.0.0 Time (mean ± σ): 16.724 s ± 0.928 s [User: 14.622 s, System: 5.743 s] Range (min … max): 15.318 s … 18.110 s 10 runs Summary 4.0.0 ran 3.92 ± 0.25 times faster than 3.6.0 ``` -------------------------------- ### Executing Binaries with Yarn bin Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/02-package-management/rulebook.mdx When needing to execute a binary from a dependency, especially with specific Node flags, use `yarn bin ` to get its path. This is an alternative to relying on the `node_modules/.bin` folder directly. ```bash yarn node --inspect $(yarn bin jest) ``` -------------------------------- ### Using findPnpApi to Get PnP API Instance Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx Shows how to use the findPnpApi function from the 'module' builtin to locate and load the closest .pnp.cjs file. It's important to use createRequire to load resolved modules. ```javascript const {createRequire, findPnpApi} = require(`module`); // We'll be able to inspect the dependencies of the module passed as first argument const targetModule = process.argv[2]; const targetPnp = findPnpApi(targetModule); const targetRequire = createRequire(targetModule); const resolved = targetPnp.resolveRequest(`eslint`, targetModule); const instance = targetRequire(resolved); // <-- important! don't use `require`! ``` -------------------------------- ### Generate Editor SDKs and Settings Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-sdks/README.md Use the 'sdks' command to generate editor SDKs and associated settings for your project. ```bash yarn sdks ``` -------------------------------- ### Generate Hello World Package Source: https://github.com/yarnpkg/berry/blob/master/packages/plugin-exec/README.md Creates a new package with a package.json and an index.js file. Ensure the build directory is set up before execution. ```typescript fs.writeFileSync(path.join(execEnv.buildDir, 'package.json'), JSON.stringify({ name: 'hello-world', version: '1.0.0', })); fs.writeFileSync(path.join(execEnv.buildDir, 'index.js'), ` module.exports = 'hello world!'; `); ``` -------------------------------- ### Register a Simple Command Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/plugin-tutorial.mdx Defines a basic command 'hello' for your plugin. No external dependencies are needed for this basic command. ```javascript module.exports = { name: `plugin-hello-world`, factory: require => { const {BaseCommand} = require(`@yarnpkg/cli`); class HelloWorldCommand extends BaseCommand { static paths = [[`hello`]]; async execute() { this.context.stdout.write(`This is my very own plugin 😎\n`); } } return { commands: [ HelloWorldCommand, ], }; } }; ``` -------------------------------- ### Create a directory for node_modules project Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/recipes.mdx Set up a new directory and an empty yarn.lock file for a project that will use node_modules. ```bash mkdir nm-packages/myproj touch nm-packages/myproj/yarn.lock ``` -------------------------------- ### Parse Bare Identifier Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.mdx Parses a module specifier into its scoped identifier (if any) and module path. Handles scoped packages starting with '@'. ```javascript PARSE_BARE_IDENTIFIER(specifier) ``` -------------------------------- ### PNP_RESOLVE Algorithm Step 1-3 Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.mdx The initial steps of the PNP_RESOLVE algorithm, handling Node.js builtins and local/absolute paths. ```text PNP_RESOLVE(specifier, parentURL) 1. Let `resolved` be **undefined** 2. If `specifier` is a Node.js builtin, then 1. Set `resolved` to `specifier` itself and return it 3. Otherwise, if `specifier` is either an absolute path or a path prefixed with "./" or "../", then 1. Set `resolved` to [`NM_RESOLVE`](#nm_resolve)`(specifier, parentURL)` and return it ``` -------------------------------- ### Build Static Website Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/README.md Generates the static content for the website into the 'build' directory, ready for deployment. ```bash yarn build ``` -------------------------------- ### Checking for PnP Environment Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx Demonstrates how to check if the current environment is running under Plug'n'Play by inspecting process.versions.pnp. This is useful for conditionally applying PnP-specific logic. ```javascript if (process.versions.pnp) { // do something with the PnP API ... } else { // fallback } ``` -------------------------------- ### List Changed Workspaces Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2021-09-25-release-3.1.mdx Get a list of workspaces that have changed compared to the main branch. Useful for scripting purposes or identifying modified packages. ```bash yarn workspaces list --since ``` -------------------------------- ### Update Yarn to Latest Stable Version Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/basics/install.mdx Update your project to use the most recent stable Yarn binary. This involves setting the version and then installing dependencies. ```bash yarn set version stable yarn install ``` -------------------------------- ### Get Package Information Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx Retrieves all stored information for a given package locator from the PnP API. This includes details about the package's dependencies and resolution. ```typescript export function getPackageInformation(locator: PackageLocator): PackageInformation; ``` -------------------------------- ### Add a package using the Portal Protocol Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/protocols/portal.mdx Use the portal: protocol to add a local package dependency. The target path must be relative and the package must exist at resolution time. ```bash yarn add react-dom@portal:./my-react-dom ``` -------------------------------- ### Enable Postinstall Scripts Per Package Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/features/security.mdx You can enable postinstall scripts for specific packages by using the `dependenciesMeta` field in your top-level `package.json`. This allows granular control over which packages can run postinstall scripts. ```json { "dependenciesMeta": { "my-package": { "builtin": true, "root": true } } } ``` -------------------------------- ### Auto-updating Dependencies Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/features/release-workflow.mdx Demonstrates how Yarn automatically updates dependent package versions within a monorepo when a package is upgraded. This applies to basic semver ranges. ```text /packages/common (1.0.0) /packages/server (depends on common@^1.0.0) /packages/client (depends on common@^1.0.0) ``` ```text /packages/common (1.1.1) /packages/server (depends on common@^1.1.1) /packages/client (depends on common@^1.1.1) ``` -------------------------------- ### Find Package Locator by Disk Location Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx Use `findPackageLocator` to get the package locator for a given disk path. This function always returns physical locators. ```typescript export function findPackageLocator(location: string): PackageLocator | null; ``` -------------------------------- ### Build Yarn CLI Source: https://github.com/yarnpkg/berry/blob/master/README.md Run this command after cloning the repository to build the Yarn CLI. Your global Yarn will then use the locally built version. ```bash yarn build:cli ``` -------------------------------- ### Check Package Versions for Release (Interactive) Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/contributing.mdx Interactively select packages that need to be released and specify their new versions. This is a required step for preparing a PR for release. ```bash yarn version check --interactive ``` -------------------------------- ### Run Command with Pnpify Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-pnpify/README.md Execute a command using the pnpify CLI, which creates a virtual node_modules folder for the command's execution context. ```bash pnpify run ``` -------------------------------- ### Get Package Locator Helper Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/03-pnp/pnp-api.mdx A helper function to simplify working with 'referencish' ranges for package dependencies. It handles the logic for resolving locators from string or tuple references. ```typescript export function getLocator(name: string, referencish: string | [string, string]): PackageLocator; ``` -------------------------------- ### Register a Hook to Modify Script Environment Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/plugin-tutorial.mdx Listens to the 'setupScriptEnvironment' hook to inject a custom environment variable 'HELLO_WORLD'. This allows plugins to influence script execution. ```javascript module.exports = { name: `plugin-hello-world`, factory: require => ({ hooks: { setupScriptEnvironment(project, scriptEnv) { scriptEnv.HELLO_WORLD = `my first plugin!`; }, }, }) }; ``` -------------------------------- ### Define a basic catalog in .yarnrc.yml Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/features/catalogs.mdx Define version ranges for dependencies in your `.yarnrc.yml` file. This serves as a central source of truth for dependency versions. ```yaml catalog: react: ^18.3.1 lodash: ^4.17.21 ``` -------------------------------- ### Add Package with Automatic @types Resolution Source: https://github.com/yarnpkg/berry/blob/master/packages/plugin-typescript/README.md Demonstrates how Yarn automatically adds the corresponding @types package when a new package is installed. This is useful for ensuring type safety in TypeScript projects. ```bash ❯ yarn/packages/plugin-typescript ❯ yarn add lodash ➤ YN0000: · Yarn X.Y.Z ➤ YN0000: ┌ Resolution step ➤ YN0000: └ Completed in 0.24s ➤ YN0000: ┌ Fetch step ➤ YN0013: │ @types/lodash@npm:4.14.121 can't be found in the cache and will be fetched from the remote registry ➤ YN0013: │ lodash@npm:4.14.0 can't be found in the cache and will be fetched from the remote registry ➤ YN0000: └ Completed in 3.63s ➤ YN0000: ┌ Link step ➤ YN0000: └ Completed in 2.75s ➤ YN0000: · Done with warnings in 6.81s ``` -------------------------------- ### Enable Hardened Mode via Environment Variable Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2023-10-23-release-4.0.mdx For CI jobs or specific environments, enable Hardened Mode by setting this environment variable. Note that this mode significantly slows down installs. ```bash export YARN_ENABLE_HARDENED_MODE=1 ``` -------------------------------- ### Incorrect node_modules string usage Source: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-doctor/README.md This example demonstrates an incorrect usage of 'node_modules' within a require statement. Such patterns are flagged by the 'no node module strings' rule as they are incompatible with Plug'n'Play. ```javascript var module = require("../node_modules/lodash"); ``` -------------------------------- ### Implement `afterAllInstalled` Hook Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/plugin-tutorial.mdx This snippet shows how to implement the `afterAllInstalled` hook to log the number of non-virtual descriptors and packages in a project. It accesses the `Project` instance provided by Yarn. ```javascript const fs = require(`fs`); const util = require(`util`); module.exports = { name: `plugin-project-info`, factory: require => { const {structUtils} = require(`@yarnpkg/core`); return { default: { hooks: { afterAllInstalled(project) { let descriptorCount = 0; for (const descriptor of project.storedDescriptors.values()) if (!structUtils.isVirtualDescriptor(descriptor)) descriptorCount += 1; let packageCount = 0; for (const pkg of project.storedPackages.values()) if (!structUtils.isVirtualLocator(pkg)) packageCount += 1; console.log(`This project contains ${descriptorCount} different descriptors that resolve to ${packageCount} packages`); } } } }; } }; ``` -------------------------------- ### Generate Editor SDKs with Yarn dlx Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/getting-started/extra/editor-sdks.mdx Use this command to generate the base SDK and specific editor settings for VSCode, Vim, and other supported tools. ```bash yarn dlx @yarnpkg/sdks vscode vim ... ``` -------------------------------- ### Enforcing Strict Package Boundaries Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/blog/2020-01-24-release-2.0.mdx This example shows an error that occurs when an application tries to access a package not declared in its dependencies. Ensure all required packages are listed in your project's dependencies. ```typescript // Error: Something that got detected as your top-level application // (because it doesn't seem to belong to any package) tried to access // a package that is not declared in your dependencies // // Required package: not-a-dependency (via "not-a-dependency") // Required by: /Users/mael/my-app/ require(`not-a-dependency`); ``` -------------------------------- ### Check Package Versions for Release Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/04-technical/contributing.mdx Verify that all package versions are correctly set for release. This command checks the current release status. ```bash yarn version check ``` -------------------------------- ### Deferred Version Record Example Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/features/release-workflow.mdx Illustrates the format of the internal record created by Yarn when using deferred versioning. This YAML file stores pending upgrades within the .yarn/versions directory. ```yaml releases: my-package@1.0.0: minor ``` -------------------------------- ### Add a package with a patch protocol Source: https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/protocols/patch.mdx Use the `patch:` protocol to add a package with a specific patch applied. The format includes the original package version and the path to the patch file. ```bash yarn add @types/react@patch:@types/react@18.0.0#./my-patches/react-types.patch ```