### Example: index.js Importing Modules Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/BundlerExamples.md This is an example of an entry point file that imports functions from a shared module ('./math/math'). It demonstrates how imported modules are processed by the bundler, especially when manual bundles are configured. ```javascript index.js: import {add, subtract, divide} from './math/math'; sideEffectNoop(divide(subtract(add(1, 2), 3), 4)); ``` -------------------------------- ### Original Module Code Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/optimizers/inline-requires/README.md Example of a module's code before optimization, showing direct require calls. ```javascript parcelRegister('abc123', function (require, module, exports) { var $def456 = require('def456'); var $ghi789 = require('ghi789'); exports.someFunction = function () { if ($def456.someOperation()) { return $ghi789.anotherOperation(); } return null; }; }); ``` -------------------------------- ### Start parcel-query REPL Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/dev/query/README.md Initiate the REPL in a project root with a .parcel-cache folder. Use commands like `.help` to see available options. ```sh $ parcel-query > .findBundleReason 27494aebac508bd8 TJbGI # Asset is main entry of bundle: false # Asset is an entry of bundle: false # Incoming dependencies contained in the bundle: { id: '3fd182662e2a6fa9', type: 'dependency', value: { specifier: '../../foo', specifierType: 0, ... ``` -------------------------------- ### Graph Visualization Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/AdjacencyList.md Illustrates a simple graph structure and its representation using doubly linked lists for outgoing and incoming edges. ```mermaid graph TD; 0 --> |a| 1 0 --> |b| 2 1 --> |c| 2 ``` ```mermaid graph LR subgraph 0[Node 0] direction LR 0o([outgoing]) --- 0oa[[a]] <--> 0ob[[b]] --- 0or([outgoingReverse]) end subgraph 1[Node 1] direction LR 1i([incoming]) --- 1ia[[a]] --- 1ir([incomingReverse]) 1o([outgoing]) --- 1oc[[c]] --- 1or([outgoingReverse]) end subgraph 2[Node 2] direction LR 2i([incoming]) --- 2ib[[b]] <--> 2ic[[c]] --- 2ir([incomingReverse]) end ``` -------------------------------- ### Install and Configure Parcel LSP Reporter Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/utils/parcelforvscode/README.md To enable inline diagnostics, install the `@parcel/reporter-lsp` package and configure Parcel to use it. This command shows how to run Parcel with the specified reporter. ```bash npm install --save-dev @parcel/reporter-lsp parcel src/index.html --reporter @parcel/reporter-lsp ``` -------------------------------- ### Async Imports Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Example of asynchronous imports in JavaScript, used for explicit code splitting. These imports do not need to load automatically and can be loaded in tandem with other bundles. ```javascript //index.js (project entry) import('./foo'); //async imports import('./bar'); //async ``` -------------------------------- ### Runtime Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt Runtimes inject synthetic assets into bundles during packaging. This example shows a runtime that logs bundle information to the console. ```APIDOC ## Runtime Plugin ### Description Runtimes inject synthetic "virtual" assets into bundles at packaging time. This can be used for registering HMR updates, loading split bundles, or bootstrapping service workers. ### Example Usage ```javascript // my-parcel-runtime-log/index.js import { Runtime } from '@parcel/plugin'; export default new Runtime({ apply({ bundle, bundleGraph, options }) { if (bundle.type !== 'js') return; const entries = bundle.getEntryAssets(); if (entries.length === 0) return; return { filePath: 'runtime-log.js', // virtual file path (won't be read from disk) isEntry: true, code: ` if (typeof window !== 'undefined') { window.__PARCEL_BUNDLE__ = ${JSON.stringify(bundle.displayName)}; console.log('[parcel] bundle loaded:', ${JSON.stringify(bundle.displayName)}); } `, }; }, }); ``` ``` -------------------------------- ### Export Star Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Symbol Propagation.md Illustrates the ambiguity introduced by `export *` when importing symbols, showing how a symbol might be reexported from multiple files. ```javascript // index.js import {a} from './other.js'; // other.js export * from './x.js'; // Is `a` reexported here... export * from './y.js'; // ... or here? Or neither? // x.js export const a = 1; // y.js export const b = 2; ``` -------------------------------- ### Requires Hoisting Examples Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Demonstrates various ways `require` statements can be used and how Parcel might hoist them. This includes direct assignments, conditional requirements, and loop initializations. ```javascript function x() { const x = require('y'); // etc. } ``` ```javascript const x = sideEffect() + require('b'); ``` ```javascript const x = sideEffect(), require('b'); ``` ```javascript const x = sideEffect() || require('b'); ``` ```javascript const x = condition ? require('a') : require('b'); ``` ```javascript if (condition) require('a'); ``` ```javascript for (let x = require('y'); x < 5; x++) {} ``` -------------------------------- ### Compress Output Files with Compressor Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt Compressors can be used to compress final output files. This example uses zlib to create a gzip compressed stream. ```javascript // my-parcel-compressor-gzip/index.js import { Compressor } from '@parcel/plugin'; import { createGzip } from 'zlib'; export default new Compressor({ compress({ stream, options }) { return { stream: stream.pipe(createGzip({ level: 9 })), type: 'gz', // appended to output file name: e.g. main.js → main.js.gz }; }, }); ``` -------------------------------- ### Example: math.js Exporting Modules Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/BundlerExamples.md This JavaScript file serves as a module entry point, exporting other modules like 'add', 'subtract', and 'divide'. It's used in conjunction with manual bundle configurations to group related code. ```javascript //math: math.js: export * from './add'; export * from './subtract'; export * from './divide'; ``` -------------------------------- ### Optimized Module Code with Deferred Requires Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/optimizers/inline-requires/README.md Example of a module's code after optimization, demonstrating deferred require calls for lazy evaluation. ```javascript parcelRegister('abc123', function (require, module, exports) { var $def456; var $ghi789; exports.someFunction = function () { if ((0, require('def456')).someOperation()) { return (0, require('ghi789')).anotherOperation(); } return null; }; }); ``` -------------------------------- ### Handle Build Events with Reporter Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt A Reporter plugin receives build lifecycle events. This example writes a build summary to a JSON file on success and logs errors to stderr on failure. ```javascript // my-parcel-reporter-json/index.js import { Reporter } from '@parcel/plugin'; import fs from 'fs'; export default new Reporter({ async report({ event, options }) { if (event.type === 'buildSuccess') { const summary = { buildTime: event.buildTime, bundles: event.bundleGraph.getBundles().map(b => ({ name: b.displayName, size: b.stats.size, filePath: b.filePath, })), }; fs.writeFileSync( 'dist/build-manifest.json', JSON.stringify(summary, null, 2), ); } if (event.type === 'buildFailure') { for (const diag of event.diagnostics) { process.stderr.write(`[ERROR] ${diag.origin}: ${diag.message}\n`); if (diag.hints?.length) { for (const h of diag.hints) process.stderr.write(` hint: ${h}\n`); } } } }, }); ``` -------------------------------- ### Ancestor Assets Calculation Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Shows the calculated ancestorAssets for a specific HTML structure with module imports. It highlights how shared code is identified and not duplicated across siblings. ```text // ancestorAssets index.html => {}, component1 => {}, component2 => {html-js-dedup/component-1.js} ``` -------------------------------- ### Scope Hoisting Example: Math Module Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Scopehoisting.md Demonstrates how scope hoisting transforms imported modules into directly accessible variables, improving minifier effectiveness. The unused 'square' function is also shown as dead code. ```javascript // math.js export function add(a, b) { return a + b; } export function square(a) { return a * a; } // index.js import {add} from './math'; console.log(add(2, 3)); ``` ```javascript function $fa6943ce8a6b29$export$add(a, b) { return a + b; } // dead code function $fa6943ce8a6b29$export$square(a) { return a * a; } console.log($fa6943ce8a6b29$export$add(2, 3)); ``` -------------------------------- ### JavaScript Output from `fold_ident` Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/swc Visitors.md Illustrates the potential JavaScript output after applying the `fold_ident` transformation, showing how all identifiers can be transformed into 'foo'. ```javascript function foo(foo) { foo.foo(foo); } const foo = {foo: foo}; class foo { #foo; foo() { foo(this.#foo); } } ``` -------------------------------- ### Sibling Bundle Asset Distribution Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Illustrates the distribution of assets across entry and sibling bundles. This example clarifies which assets are available to each bundle based on load order and dependencies. ```text Entry Bundle => [index.html] Sibling Bundle 1 => [component1, obj.js] Sibling Bundle 2 => [component2] ``` -------------------------------- ### Exports Hoisting Examples Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Illustrates different methods of exporting module members, including direct assignments to `exports`, reassignments of `exports`, and accessing `module` non-statically. Also covers `eval` and top-level returns. ```javascript // Exports re-assigned exports.foo = 2; exports = {}; exports.bar = 3; ``` ```javascript ({exports} = something); ``` ```javascript // Module accessed non-statically sideEffect(module); ``` ```javascript // Eval eval('exports.foo = 2'); ``` ```javascript // Top-level return return; ``` -------------------------------- ### Asset Graph Deferring Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Deferring.md Illustrates an asset graph where a 'Switch' asset is deferred because it's not yet used. The `deferred` flag on `AssetGroupLibSwitch` indicates this state. ```mermaid graph TD; AssetA -->DependencyLibA[DependencyLibA:Button] -->AssetGroupLib[AssetGroupLib
hasDeferred] -->AssetLib[AssetLib
hasDeferred]; AssetLib -->DependencyLibButton[DependencyLibButton:Button] -->AssetGroupLibButton -->AssetLibButton; AssetLib -->DependencyLibSwitch[DependencyLibSwitch:Switch
hasDeferred] -->AssetGroupLibSwitch[AssetGroupLibSwitch
deferred]; classDef asset fill:orange,stroke:orange; classDef dep fill:lime,stroke:lime; class AssetA asset; class AssetLib asset; class AssetLibButton asset; class DependencyLibA dep; class DependencyLibButton dep; class DependencyLibSwitch dep; ``` -------------------------------- ### ESM Circular Import Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Scopehoisting.md Shows a scenario with circular imports in ESM where a variable is accessed before initialization. ```javascript // index.js import {func} from './other.js'; func(); // ReferenceError: Cannot access 'value' before initialization export const value = 1; // other.js import {value} from './index.js'; export function func() { return value + 1; } ``` -------------------------------- ### Linking items in SharedTypeMap with collisions Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/AdjacencyList.md This example demonstrates linking items into a SharedTypeMap, showing how collisions are handled by chaining through the NEXT field. It illustrates the concept of hash buckets and linked lists within the hash table. ```javascript // map.link(hash, address, type) map.link(0, map.getNextAddress(), 1) map.link(1, map.getNextAddress(), 2) map.link(2, map.getNextAddress(), 3) map.link(0, map.getNextAddress(), 1) ``` -------------------------------- ### Inject Virtual Assets with Runtime Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt Use a Runtime plugin to inject synthetic assets into bundles. This example logs bundle information to the console when a JavaScript bundle is loaded. ```javascript // my-parcel-runtime-log/index.js import { Runtime } from '@parcel/plugin'; export default new Runtime({ apply({ bundle, bundleGraph, options }) { if (bundle.type !== 'js') return; const entries = bundle.getEntryAssets(); if (entries.length === 0) return; return { filePath: 'runtime-log.js', // virtual file path (won't be read from disk) isEntry: true, code: ` if (typeof window !== 'undefined') { window.__PARCEL_BUNDLE__ = ${JSON.stringify(bundle.displayName)}; console.log('[parcel] bundle loaded:', ${JSON.stringify(bundle.displayName)}); } `, }; }, }); ``` -------------------------------- ### Build with Parcel from Monorepo Source: https://github.com/parcel-bundler/parcel/blob/v2/CONTRIBUTING.md Use this command to build a project using a local Parcel build from the monorepo. Ensure no conflicting Parcel packages are installed in the target project. ```sh /path/to/monorepo/packages/core/parcel/src/bin.js build src/index.html ``` -------------------------------- ### Bundle Reuse Logic Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/BundlerExamples.md Illustrates how Parcel reuses existing bundles when assets are required by multiple entry points or async imports. This example shows the 'ReachableRoots' concept for determining bundle placement. ```javascript //index.js import('./foo'); import('./bar'); ``` ```javascript //a.js import foo from './foo'; ``` ```javascript //bar.js import foo from './a'; import bar from './b'; import styles from './styles.css'; import html from './local.html'; ``` ```javascript // foo.js import a from './a'; import b from './b'; export default a; ``` -------------------------------- ### Create a Custom Markdown Transformer Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt Implement a Parcel Transformer plugin to convert Markdown assets to HTML. This example uses the 'marked' library and demonstrates the `loadConfig`, `transform`, and `invalidateOnFileChange` hooks. ```javascript // my-parcel-transformer-md/index.js import { Transformer } from '@parcel/plugin'; import { marked } from 'marked'; export default new Transformer({ // (Optional) Load external config once per build async loadConfig({ config }) { const cfg = await config.getConfig(['.markedrc', '.markedrc.json'], { packageKey: 'marked', }); if (cfg) config.addDevDependency({ specifier: 'marked', resolveFrom: cfg.filePath }); return cfg?.contents ?? {}; }, // Transform the asset — must return MutableAsset or TransformerResult[] async transform({ asset, config, logger }) { if (asset.type !== 'md') return [asset]; const md = await asset.getCode(); const html = marked(md, config); asset.type = 'html'; asset.setCode(html); // Invalidate cache when config files change asset.invalidateOnFileChange('.markedrc'); logger.info({ message: `Compiled ${asset.filePath}` }); return [asset]; }, }); ``` -------------------------------- ### Reporter Plugin Source: https://context7.com/parcel-bundler/parcel/llms.txt Reporters receive build lifecycle events and can perform side effects like writing to stdout or sending metrics. This example writes a build summary to a JSON file on success and logs errors on failure. ```APIDOC ## Reporter Plugin ### Description Reporters receive every build lifecycle event (e.g., `buildStart`, `buildSuccess`, `buildFailure`). They can be used to write to stdout, send metrics, or perform other side-effect work. ### Example Usage ```javascript // my-parcel-reporter-json/index.js import { Reporter } from '@parcel/plugin'; import fs from 'fs'; export default new Reporter({ async report({ event, options }) { if (event.type === 'buildSuccess') { const summary = { buildTime: event.buildTime, bundles: event.bundleGraph.getBundles().map(b => ({ name: b.displayName, size: b.stats.size, filePath: b.filePath, })), }; fs.writeFileSync( 'dist/build-manifest.json', JSON.stringify(summary, null, 2), ); } if (event.type === 'buildFailure') { for (const diag of event.diagnostics) { process.stderr.write(`[ERROR] ${diag.origin}: ${diag.message}\n`); if (diag.hints?.length) { for (const h of diag.hints) process.stderr.write(` hint: ${h}\n`); } } } }, }); ``` ``` -------------------------------- ### Asset Graph Undeferring Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Deferring.md Shows the asset graph after a new dependency ('Switch') is added, causing the previously deferred 'Switch' asset to be undeferred and transformed. The `deferred` flag is cleared, and the asset node is created. ```mermaid graph TD; AssetA -->DependencyLibA[DependencyLibA:Button] -->AssetGroupLib; AssetB -->DependencyLibB[DependencyLibB:Switch] -->AssetGroupLib; AssetGroupLib[AssetGroupLib
hasDeferred] -->AssetLib[AssetLib
hasDeferred]; AssetLib -->DependencyLibButton[DependencyLibButton:Button] -->AssetGroupLibButton -->AssetLibButton; AssetLib -->DependencyLibSwitch[DependencyLibSwitch:Switch
hasDeferred] -->AssetGroupLibSwitch[AssetGroupLibSwitch
deferred]; AssetGroupLibSwitch -->AssetLibSwitch; classDef asset fill:orange,stroke:orange; classDef dep fill:lime,stroke:lime; class AssetA,AssetB,AssetLib,AssetLibButton asset; class DependencyLibA,DependencyLibB,DependencyLibButton,DependencyLibSwitch dep; style AssetLibSwitch fill:transparent,stroke-dasharray: 5 5,stroke:orange; linkStyle 10 stroke-dasharray: 5 5,stroke-width: 1.5; ``` -------------------------------- ### Serve HTML with Parcel Source: https://context7.com/parcel-bundler/parcel/llms.txt Starts a local development server with Hot Module Replacement (HMR). Defaults to port 1234. Use options to customize port, HTTPS, auto-open, public URL, host binding, disable HMR, enable lazy mode, or control logging and caching. ```bash parcel serve src/index.html ``` ```bash parcel serve src/index.html --port 3000 --https --open ``` ```bash parcel serve src/index.html --public-url /app/ --host 0.0.0.0 --port 8080 ``` ```bash parcel serve src/index.html --no-hmr --https --cert ./cert.pem --key ./key.pem ``` ```bash parcel serve src/index.html --lazy ``` ```bash parcel serve src/index.html --lazy "src/routes/**" --lazy-exclude "src/routes/home/**" ``` ```bash parcel serve src/index.html --log-level verbose --no-cache ``` -------------------------------- ### Handle Multiple CSS Imports in Entry Points Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/BundlerExamples.md Demonstrates how Parcel handles multiple CSS imports from different JavaScript entry points, including async imports. This example shows the initial state of the bundle graph before merging. ```javascript //entry.js import './main.css'; import './Foo/foo.css'; import('./Foo'); ``` ```javascript // Foo/foo.js import './foo.css'; export default function () { return 'foo'; } ``` -------------------------------- ### Configure VSCode Launch Configuration Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/utils/parcelforvscode/CONTRIBUTING.md Set up the `launch.json` file in VSCode to launch the Parcel for VSCode extension in a development host. Ensure the `args` correctly point to the workspace folder and the extension development path. ```json { "version": "0.2.0", "configurations": [ { "args": [ "${workspaceFolder}/packages/examples/kitchen-sink", // Change this project "--extensionDevelopmentPath=${workspaceFolder}/packages/utils/parcelforvscode" ], "name": "Launch Parcel for VSCode Extension", "outFiles": [ "${workspaceFolder}/packages/utils/parcelforvscode/out/**/*.js" ], "preLaunchTask": "Watch VSCode Extension", "request": "launch", "type": "extensionHost" } ] } ``` -------------------------------- ### Isolated Dependency Example Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Example of an isolated dependency in JavaScript, where the imported asset is treated as a separate bundle and cannot share assets with other bundles. This is often used for assets like HTML or images. ```javascript //bar.js import styles from './styles.css'; import html from './local.html'; //isolated ``` -------------------------------- ### Cleanup with parcel-link unlink Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/dev/parcel-link/README.md Use the `unlink` command to restore your project to its default Parcel installation. ```sh $ parcel-link unlink [options] [packageRoot] ``` -------------------------------- ### Bundle Creation Options Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Details the various options available when creating a bundle. These options provide information about the bundle's contents, packaging, target, and naming conventions, allowing for flexible bundle configuration. ```javascript uniqueKey: opts.uniqueKey, // can be read by namers for more functionality assets: new Set([asset]), // The set of all assets in the bundle mainEntryAsset: asset, // The main or initial asset of the bundle, can be null size: asset.stats.size, // size sourceBundles: new Set(), // The bundles which load and require this bundle target: opts.target, // Target for output purposes type: opts.type ?? asset.type, // type, js, html etc env: opts.env ?? asset.env, needsStableName: Boolean(opts.needsStableName), // whether to hash the final name bundleBehavior: opts.bundleBehavior ?? asset.bundleBehavior, manualSharedBundle: opts.manualSharedBundle, ``` -------------------------------- ### InitialParcelOptions Source: https://context7.com/parcel-bundler/parcel/llms.txt Reference for all configuration options accepted by `new Parcel(options)` and internally by the CLI. ```APIDOC ## `InitialParcelOptions` — Full Configuration Reference ### Description All options accepted by `new Parcel(options)` and internally by the CLI. ### Configuration Options #### Entry points - **entries**: Array of entry file paths (e.g., `['src/index.html', 'src/admin.html']`). #### Config - **config**: Explicit `.parcelrc` path or package name (e.g., `'./custom.parcelrc'`). - **defaultConfig**: Fallback config when no `.parcelrc` exists (e.g., `'@parcel/config-default'`). #### Build mode - **mode**: Build mode ('development', 'production', or any custom string). #### Targets - **targets**: Target configurations (e.g., `['modern', 'legacy']` or `{ name: TargetDescriptor }`). #### Cache - **shouldDisableCache**: Boolean to disable the cache (default: `false`). - **cacheDir**: Directory for cache files (e.g., `'.parcel-cache'`). #### Watcher - **watchDir**: Directory to watch (default: `'.'`). - **watchBackend**: Watcher backend ('watchman', 'inotify', 'fs-events', 'brute-force', 'windows'). - **watchIgnore**: Array of patterns to ignore during watching (e.g., `['.git', 'dist']`). #### Dev server / HMR - **serveOptions**: Options for the development server. - **port**: Server port (default: `1234`). - **host**: Server host (default: `'localhost'`). - **https**: HTTPS configuration (boolean or object with `cert` and `key`). - **publicUrl**: Public URL for the server (default: `/`). - **cors**: Enable CORS (boolean). - **hmrOptions**: Options for Hot Module Replacement. - **port**: HMR port (default: `1234`). - **host**: HMR host (default: `'localhost'`). - **cors**: Enable CORS for HMR (boolean). #### Output - **shouldContentHash**: Boolean to enable content hashing for output files (default: `false`). #### Optimization - **defaultTargetOptions**: Options for default target optimization. - **shouldOptimize**: Boolean to enable optimization (default: `false`). - **shouldScopeHoist**: Boolean to enable scope hoisting (default: `false`). - **sourceMaps**: Boolean to enable source maps (default: `false`). - **publicUrl**: Public URL for assets (e.g., `'https://cdn.example.com/'`). - **distDir**: Output directory (e.g., `path.resolve('dist')`). - **engines**: Engine constraints (e.g., `{ browsers: ['> 0.25%', 'not dead'] }`). - **outputFormat**: Output format ('esmodule', 'commonjs', 'global'). - **isLibrary**: Boolean indicating if the output is a library (default: `false`). #### Lazy builds - **shouldBuildLazily**: Boolean to enable lazy building (default: `false`). - **lazyIncludes**: Array of patterns to include for lazy building. - **lazyExcludes**: Array of patterns to exclude for lazy building. #### Incremental bundling - **shouldBundleIncrementally**: Boolean to enable incremental bundling (default: `false`). #### Logging / diagnostics - **logLevel**: Logging level ('none', 'error', 'warn', 'info', 'verbose'). - **detailedReport**: Options for detailed reporting (e.g., `{ assetsPerBundle: 10 }`). #### Profiling / tracing - **shouldProfile**: Boolean to enable profiling (default: `false`). - **shouldTrace**: Boolean to enable tracing (default: `false`). #### Misc - **shouldAutoInstall**: Boolean to enable automatic installation (default: `false`). - **shouldPatchConsole**: Boolean to patch console methods (default: `false`). #### Custom file system - **inputFS**: Custom input file system implementation. - **outputFS**: Custom output file system implementation. #### Additional reporters - **additionalReporters**: Array of additional reporter configurations. #### Feature flags - **featureFlags**: Object for feature flags (e.g., `{ useWatchmanWatcher: true }`). #### Environment variables - **env**: Object for environment variables to be injected into the build (e.g., `{ NODE_ENV: 'production', API_URL: 'https://api.example.com' }`). ### Request Example ```javascript import Parcel from '@parcel/core'; import { NodeFS, MemoryFS } from '@parcel/fs'; import path from 'path'; const parcel = new Parcel({ entries: ['src/index.html'], mode: 'development', defaultTargetOptions: { publicUrl: '/', distDir: path.resolve('dist'), }, env: { NODE_ENV: 'development' }, }); ``` ``` -------------------------------- ### Specifying Package Root Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/dev/parcel-link/README.md Use the `packageRoot` argument to link to Parcel packages located in a different directory than where `parcel-link` is installed. ```sh $ parcel-link /path/to/parcel/packages ``` -------------------------------- ### Creating an Entry Bundle Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Illustrates the creation of an entry bundle using the `createBundle` function. It requires the asset, target, and a `needsStableName` flag, which determines if the bundle name will include a hash. ```javascript let bundle = createBundle({ asset, target: nullthrows(dependency.target), needsStableName: dependency.isEntry, }); ``` -------------------------------- ### Safe CommonJS export patterns Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Examples of CommonJS export assignments that are statically analyzable. These include direct assignments to exports or module.exports. ```js exports.foo = 2; module.exports.foo = 2; this.foo = 2; exports['foo'] = 2; function test() { exports.foo = 2; } ``` -------------------------------- ### Create and Use a Node.js ESM Resolver Source: https://github.com/parcel-bundler/parcel/blob/v2/crates/parcel-resolver/README.md Demonstrates creating a Node.js compatible ES module resolver with a cache and resolving a module specifier. Ensure the cache is created once per build for up-to-date information. ```rust use parcel_resolver::{Cache, Resolver, SpecifierType, ResolutionAndQuery}; use std::path::Path; let cache = Cache::default(); let resolver = Resolver::node_esm(Path::new("/path/to/project-root"), &cache); let res = resolver.resolve( "lodash", Path::new("/path/to/project-root/index.js"), SpecifierType::Esm ); if let Ok(ResolutionAndQuery { resolution, query }) = res.result { // Do something with the resolution! } ``` -------------------------------- ### Safe CommonJS require patterns Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Examples of CommonJS require statements that can be fully statically analyzed. These are typically direct imports of named exports. ```js require('y'); require('y').foo; require('y').foo(); const y = require('y'); const x = require('y').x; const {x} = require('y'); const {x: y} = require('y'); const {x = 2} = require('y'); // Safe but needs to be split into separate declarations. const a = sideEffect(), b = require('y'); ``` -------------------------------- ### Single Build with `new Parcel().run()` Source: https://context7.com/parcel-bundler/parcel/llms.txt Performs a single production build using the Parcel API. It configures build options such as entry points, output directory, optimization, and source maps, then executes the build and logs the results or errors. ```APIDOC ## Single Build with `new Parcel().run()` ### Description Performs a single production build using the Parcel API. It configures build options such as entry points, output directory, optimization, and source maps, then executes the build and logs the results or errors. ### Method `new Parcel(options).run()` ### Parameters #### Options - **entries** (string[]) - Required - An array of entry points for the build. - **defaultConfig** (string) - Required - Path to the default Parcel configuration. - **mode** ('production' | 'development') - Required - The build mode. - **defaultTargetOptions** (object) - Optional - Default options for all targets. - **distDir** (string) - Required - The output directory for the build. - **shouldOptimize** (boolean) - Optional - Whether to optimize the build. - **shouldScopeHoist** (boolean) - Optional - Whether to scope hoist modules. - **sourceMaps** (boolean) - Optional - Whether to generate source maps. - **publicUrl** (string) - Optional - The public URL for assets. - **logLevel** ('info' | 'verbose' | 'error' | 'warn' | 'none') - Optional - The logging level. - **shouldDisableCache** (boolean) - Optional - Whether to disable the cache. - **cacheDir** (string) - Optional - The directory for the cache. - **shouldAutoInstall** (boolean) - Optional - Whether to automatically install missing dependencies. - **env** (object) - Optional - Environment variables to set for the build. - **additionalReporters** (object[]) - Optional - Additional reporters to use for the build. ### Request Example ```javascript import Parcel from '@parcel/core'; import path from 'path'; const parcel = new Parcel({ entries: ['src/index.html'], defaultConfig: require.resolve('@parcel/config-default'), mode: 'production', defaultTargetOptions: { distDir: path.resolve('dist'), shouldOptimize: true, shouldScopeHoist: true, sourceMaps: true, publicUrl: 'https://cdn.example.com/', }, logLevel: 'info', shouldDisableCache: false, cacheDir: '.parcel-cache', shouldAutoInstall: false, env: { NODE_ENV: 'production' }, additionalReporters: [ { packageName: '@parcel/reporter-json', resolveFrom: path.resolve('index.js'), }, ], }); try { const { bundleGraph, buildTime, changedAssets } = await parcel.run(); console.log(`Build succeeded in ${buildTime}ms`); } catch (err) { // Handle errors process.exit(1); } ``` ### Response #### Success Response (200) - **bundleGraph** (object) - The resulting bundle graph. - **buildTime** (number) - The time taken for the build in milliseconds. - **changedAssets** (Set) - A set of assets that were changed during the build. #### Response Example ```json { "bundleGraph": { /* ... */ }, "buildTime": 1234, "changedAssets": [ /* ... */ ] } ``` ``` -------------------------------- ### Linking in a Monorepo with Globs Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/dev/parcel-link/README.md In monorepos, specify globs for `node_modules` locations where Parcel packages might be installed. Include `node_modules` if you want to preserve the default behavior. ```sh $ parcel-link --node-modules-globs build-tools/*/node_modules build-tools/parcel/*/node_modules ``` ```sh $ parcel-link -g build-tools/*/node_modules -g build-tools/parcel/*/node_modules -g node_modules ``` -------------------------------- ### Non-static CommonJS require patterns Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Examples of CommonJS require statements that cannot be fully statically analyzed and require namespace objects. These often involve dynamic property access. ```js require('x')[something]; const x = require('x')[something]; const x = require('x'); x[something]; const {x, ...y} = require('x'); x = require('y'); ({x} = require('y')); ``` -------------------------------- ### Configure Multiple Targets in package.json Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/BundlerExamples.md Specify multiple build targets in your package.json to create distinct output directories and source files for each target. ```json "targets": { "main1": { "distDir": "./dist/main1", "source": "./src/main1/index.html", "publicUrl": "./" }, "main2": { "distDir": "./dist/main2", "source": "./src/main2/index.html", "publicUrl": "./" } }, ``` -------------------------------- ### Inline JavaScript Example Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/core/integration-tests/test/integration/html-inline-js/index.html This snippet shows how to declare variables and define a function for inline JavaScript execution within an HTML file. Parcel processes this code directly. ```javascript var hello = "Hello"; let getHello = (someArgument) => { return someArgument; } var world = "world"; var end = "!"; console.log(`${hello} ${world}${end}`); ``` -------------------------------- ### Non-static CommonJS export patterns Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/hoist.md Examples of CommonJS export assignments that are not statically analyzable and require dynamic handling. These often involve dynamic property names or side effects. ```js exports[foo] = 2; module.exports[foo] = 2; this[foo] = 2; sideEffect(exports); sideEffect(module.exports); ``` -------------------------------- ### Build for Production with Parcel Source: https://context7.com/parcel-bundler/parcel/llms.txt Bundles assets for production, enabling minification, scope hoisting, and content hashing by default. NODE_ENV is automatically set to 'production'. Options allow customization of the output directory, disabling optimizations, scope hoisting, or content hashing, specifying targets, building multiple entries, generating reports, using custom configs, or setting public URLs. ```bash parcel build src/index.html ``` ```bash parcel build src/index.html --dist-dir public/ ``` ```bash parcel build src/index.html --no-optimize ``` ```bash parcel build src/index.html --no-scope-hoist ``` ```bash parcel build src/index.html --no-content-hash ``` ```bash parcel build --target browserModern ``` ```bash parcel build src/index.html src/admin.html ``` ```bash parcel build src/index.html --detailed-report 20 ``` ```bash parcel build src/index.html --config ./.parcelrc.prod ``` ```bash parcel build src/index.html --public-url https://cdn.example.com/ ``` -------------------------------- ### Basic CSS and HTML Structure Source: https://github.com/parcel-bundler/parcel/blob/v2/packages/core/integration-tests/test/integration/htmlnano-config/index.html Demonstrates a simple HTML structure with basic CSS rules. This is used to test HTMLNano's ability to parse and potentially optimize CSS within HTML. ```html Test h1 { color: red } div { color: #0000ff } a {} div { font-size: 20px } ``` -------------------------------- ### Implementing `fold_ident` Visitor Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/swc Visitors.md Shows a basic implementation of the `fold_ident` method for modifying Ident nodes within the AST. The example replaces any identifier with a new one named 'foo'. ```rust fn fold_ident(&mut self, node: &Ident) -> Ident { Ident::new("foo".into(), DUMMY_SP) } ``` -------------------------------- ### Querying Bundle Root Graph Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/DefaultBundler.md Demonstrates how to query the bundleRootGraph for connected node IDs using all edge types. This is used to understand parallel and asynchronous relationships between bundles. ```javascript bundleRootGraph.getNodeIdsConnectedTo(id, ALL_EDGE_TYPES); ``` -------------------------------- ### Structured Error Reporting with ThrowableDiagnostic Source: https://context7.com/parcel-bundler/parcel/llms.txt Use `@parcel/diagnostic` to emit rich errors with source code highlights, hints, and documentation links. This example shows throwing a structured error from a transformer. ```javascript import ThrowableDiagnostic, { md } from '@parcel/diagnostic'; // Throw a structured error from within a transformer function assertValidConfig(value, filePath, loc) { if (typeof value !== 'string') { throw new ThrowableDiagnostic({ diagnostic: { message: md`Expected a string, got `${typeof value}``, origin: 'my-transformer', codeFrames: [ { filePath, codeHighlights: [ { start: { line: loc.line, column: loc.column }, end: { line: loc.line, column: loc.column + 10 }, message: 'This value must be a string', }, ], }, ], hints: [ 'Change the value to a quoted string, e.g. "my-value"', ], documentationURL: 'https://example.com/docs/my-transformer#config', }, }); } } // Log a non-fatal warning from a plugin logger.warn({ message: 'Deprecated option "foo" — use "bar" instead', hints: ['See https://example.com/migration for upgrade instructions'], }); ``` -------------------------------- ### Matching Glob on File Path and Type Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/ManualBundling.md This step involves matching the glob pattern defined in the manual bundle configuration against the asset's file path and type. It's the first step in overriding traditional code split bundles. ```javascript // MSB Step 1: Match glob on file path and type for any asset let manualSharedBundleKey; let manualSharedObject = manualAssetToConfig.get(childAsset); ``` -------------------------------- ### Full Parcel Initialization Configuration Source: https://context7.com/parcel-bundler/parcel/llms.txt Configure Parcel with a comprehensive set of options for entries, config, mode, targets, cache, watcher, dev server, HMR, output, optimization, lazy builds, incremental bundling, logging, profiling, custom file systems, reporters, feature flags, and environment variables. ```javascript import Parcel from '@parcel/core'; import { NodeFS, MemoryFS } from '@parcel/fs'; import path from 'path'; const parcel = new Parcel({ // ── Entry points ───────────────────────────────────────────────────────── entries: ['src/index.html', 'src/admin.html'], // ── Config ─────────────────────────────────────────────────────────────── config: './custom.parcelrc', // explicit .parcelrc path or package name defaultConfig: '@parcel/config-default', // fallback config when no .parcelrc exists // ── Build mode ─────────────────────────────────────────────────────────── mode: 'production', // 'development' | 'production' | any string // ── Targets ────────────────────────────────────────────────────────────── targets: ['modern', 'legacy'], // or { name: TargetDescriptor } // ── Cache ──────────────────────────────────────────────────────────────── shouldDisableCache: false, cacheDir: '.parcel-cache', // ── Watcher ────────────────────────────────────────────────────────────── watchDir: '.', watchBackend: 'watchman', // 'watchman' | 'inotify' | 'fs-events' | 'brute-force' | 'windows' watchIgnore: ['.git', 'dist'], // ── Dev server / HMR ───────────────────────────────────────────────────── serveOptions: { port: 1234, host: 'localhost', https: { cert: './cert.pem', key: './key.pem' }, // or just `true` publicUrl: '/', cors: true, }, hmrOptions: { port: 1234, host: 'localhost', cors: false }, // ── Output ─────────────────────────────────────────────────────────────── shouldContentHash: true, // ── Optimization ───────────────────────────────────────────────────────── defaultTargetOptions: { shouldOptimize: true, shouldScopeHoist: true, sourceMaps: true, publicUrl: 'https://cdn.example.com/', distDir: path.resolve('dist'), engines: { browsers: ['> 0.25%', 'not dead'] }, outputFormat: 'esmodule', // 'esmodule' | 'commonjs' | 'global' isLibrary: false, }, // ── Lazy builds ────────────────────────────────────────────────────────── shouldBuildLazily: true, lazyIncludes: ['src/routes/**'], lazyExcludes: ['src/routes/home/**'], // ── Incremental bundling ───────────────────────────────────────────────── shouldBundleIncrementally: true, // ── Logging / diagnostics ──────────────────────────────────────────────── logLevel: 'info', // 'none' | 'error' | 'warn' | 'info' | 'verbose' detailedReport: { assetsPerBundle: 10 }, // ── Profiling / tracing ────────────────────────────────────────────────── shouldProfile: false, shouldTrace: false, // ── Misc ───────────────────────────────────────────────────────────────── shouldAutoInstall: true, shouldPatchConsole: true, // ── Custom file system ─────────────────────────────────────────────────── inputFS: new NodeFS(), outputFS: new MemoryFS(workerFarm), // ── Additional reporters ───────────────────────────────────────────────── additionalReporters: [ { packageName: '@parcel/reporter-json', resolveFrom: path.resolve('index.js') }, ], // ── Feature flags ──────────────────────────────────────────────────────── featureFlags: { useWatchmanWatcher: true }, // ── Environment variables injected into the build ──────────────────────── env: { NODE_ENV: 'production', API_URL: 'https://api.example.com' }, }); ``` -------------------------------- ### Constructing JsWord Identifiers Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/swc Visitors.md Demonstrates creating JsWord instances from strings and using the js_word! macro for efficient interned strings. Shows how to access the symbol and syntax context of an Ident node. ```rust let x: JsWord = "something".into(); let y: JsWord = js_word!("require") // or "URL", "default", "eval", ... let ident: Ident; // the ast node ident.sym // the JsWord "string" ident.span.ctxt // the syntax context ``` -------------------------------- ### Handling Circular Reexports in JavaScript Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Symbol Propagation.md This example demonstrates a common circular reexport scenario between two JavaScript modules. It highlights how imports and exports can create cycles that require careful handling during symbol propagation. ```javascript // index.js import {b} from './other.js'; export const a = 1; console.log(b); // other.js export {a as b} from './index.js'; ``` -------------------------------- ### Parse JSON with Comments using serde_json and StripComments Source: https://github.com/parcel-bundler/parcel/blob/v2/crates/parcel-resolver/src/json_comments_rs/README.md Use `StripComments::new` to wrap input data before passing it to `serde_json::from_reader`. This example demonstrates parsing JSON containing block and line comments. ```rust use serde_json::{Result, Value}; use json_comments::StripComments; fn main() -> Result<()> { // Some JSON input data as a &str. Maybe this comes form the user. let data = r#"# { "name": /* full */ "John Doe", "age": 43, "phones": [ "+44 1234567", // work phone "+44 2345678" // home phone ] }"#; // Strip the comments from the input (use `as_bytes()` to get a `Read`). let stripped = StripComments::new(data.as_bytes()); // Parse the string of data into serde_json::Value. let v: Value = serde_json::from_reader(stripped)?; println!("Please call {} at the number {}", v["name"], v["phones"][0]); Ok(()) } ``` -------------------------------- ### Skipping Assets with Reexports Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/Scopehoisting.md Illustrates how Parcel can skip entire assets if they only contain reexports and are not directly used or have side effects. This example shows how 'exports-b.js' and 'exports-c.js' might be skipped due to symbol propagation and deferring. ```javascript import {a} from './lib.js'; console.log(a); // lib.js, asset gets skipped export * from './exports-a.js'; // dep used, not skipped export * from './exports-b.js'; // dep skipped with symbol propagation export {c} from './exports-c.js'; // dep skipped with deferring ``` -------------------------------- ### Implementing a Custom swc Visitor Source: https://github.com/parcel-bundler/parcel/blob/v2/docs/swc Visitors.md Demonstrates how to implement a custom visitor struct in Rust that derives the `Visit` trait. This is useful for analyzing AST nodes without modifying them. Ensure the `Visit` trait is imported. ```rust struct Foo { some_state: Vec } impl Visit for Foo { // Default implementation for all other nodes: // fn visit_module(&mut self, node: &Ident) { // node.visit_children_with(self); // } fn visit_expr(&mut self, node: &Expr) { println!("Some expression!"); node.visit_children_with(self); } fn visit_ident(&mut self, node: &Ident) { self.some_state.push(node.sym); } } func main(){ // ... let myVisitor = Foo { some_state: vec![] }; module.visit_with(&mut myVisitor); // ... } ```