### Start Local Development Server Source: https://github.com/parcel-bundler/website/blob/v2/README.md Run these commands to start a local development server for the Parcel v2 website. Ensure you have Yarn installed. ```bash yarn yarn serve ``` -------------------------------- ### Install React and React DOM Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md Install the necessary React libraries into your project using yarn. ```shell yarn add react react-dom ``` -------------------------------- ### Install Flow for Existing Projects Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md Add Flow support to an existing project by installing the `flow-bin` development dependency. ```shell yarn add flow-bin --dev ``` -------------------------------- ### Install ESLint Dependencies Source: https://github.com/parcel-bundler/website/blob/v2/src/migration/cra.md Install ESLint and the react-app configuration for linting your project code. ```bash npm install eslint eslint-config-react-app --save-dev ``` -------------------------------- ### Start Development Server Source: https://github.com/parcel-bundler/website/blob/v2/src/features/cli.md Starts a development server that rebuilds the app on file changes and supports hot reloading. This is the default command and can be invoked directly with entry points. ```bash parcel src/index.html ``` -------------------------------- ### Install PostHTML Plugin Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/html.md Install PostHTML plugins using yarn. This command installs `posthtml-doctype` as a development dependency. ```bash yarn add posthtml-doctype --dev ``` -------------------------------- ### VersionMap Example Source: https://github.com/parcel-bundler/website/blob/v2/api/index.html An example of a VersionMap, which represents a resolved browserslist. It maps browser names to their versions. ```json { edge: '76', firefox: '67', chrome: '63', safari: '11.1', opera: '50', } ``` -------------------------------- ### Define Environment Variables in .env File Source: https://github.com/parcel-bundler/website/blob/v2/src/features/node-emulation.md This example shows how to define environment variables using the `.env` file format. Lines starting with '#' are comments. Supports `NAME=value` pairs. ```dotenv APP_NAME=test API_KEY=12345 ``` -------------------------------- ### Install Compression Packages Source: https://github.com/parcel-bundler/website/blob/v2/src/features/production.md Install the necessary Parcel compressors for Gzip and Brotli as development dependencies. ```shell yarn add @parcel/compressor-gzip @parcel/compressor-brotli --dev ``` -------------------------------- ### Basic Runtime Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/runtime.md This is a basic example of a Runtime plugin. It demonstrates how to define a plugin that accepts a bundle and bundleGraph, and returns assets to be inserted. The actual logic for generating assets is omitted. ```javascript import { Runtime } from "@parcel/plugin"; export default new Runtime({ async apply({ bundle, bundleGraph }) { // ... return assets; }, }); ``` -------------------------------- ### Static Rendering Example Source: https://github.com/parcel-bundler/website/blob/v2/src/blog/v2-14-0/v2-14-0.md This example shows how to render a page with navigation links using static rendering. It receives a list of pages and the current page as props to generate the HTML structure. ```jsx export default function Page({pages, currentPage}) { return ( {currentPage.name} ); } ``` -------------------------------- ### Reporter Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/plugins.html A Reporter plugin listens for build events and reports information. This example logs the number of bundles built and the build time upon successful completion. ```javascript import {Reporter} from '@parcel/plugin'; export default new Reporter({ report({event}) { if (event.type === 'buildSuccess') { let bundles = event.bundleGraph.getBundles(); process.stdout.write(`✨ Built ${bundles.length} bundles in ${event.buildTime}ms!\n`); } } }); ``` -------------------------------- ### Report Build Start Event Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/reporter.md Logs a message to stdout when a build is started. This event is emitted at the start of each rebuild in watch mode. ```javascript import {Reporter} from '@parcel/plugin'; export default new Reporter({ report({event}) { if (event.type === 'buildStart') { process.stdout.write('Started build!\n'); } } }); ``` -------------------------------- ### Install Jest Dependencies Source: https://github.com/parcel-bundler/website/blob/v2/src/migration/cra.md Install Jest and related packages for testing. This is a prerequisite for migrating your test scripts. ```bash npm install jest jest-watch-typeahead babel-jest babel-preset-react-app identity-obj-proxy --save-dev ``` -------------------------------- ### Example CSS with PostCSS Import Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/css.md An example CSS file demonstrating the use of @import to include other CSS files and CSS variables. ```css @import "./config/index.css"; html { background-color: var(--varColor); } .icon { width: 50px; height: 50px; background-image: var(--varIcon); } ``` -------------------------------- ### Simple CoffeeScript 'Hello world!' example Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/coffeescript.md A basic CoffeeScript file that logs a message to the console. This demonstrates the minimal syntax required. ```coffeescript console.log 'Hello world!' ``` -------------------------------- ### Compressor Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/plugins.html A Compressor plugin handles compression of the bundled output. This example uses a gzip stream to compress the content and sets the output type to 'gz'. ```javascript import {Compressor} from '@parcel/plugin'; export default new Compressor({ async compress({stream}) { return { stream: gzipStream(stream), type: 'gz' }; }, }); ``` -------------------------------- ### Start Parcel development server with npm Source: https://github.com/parcel-bundler/website/blob/v2/src/getting-started/webapp.md Run this command to start the Parcel development server using npx, pointing to your HTML entry file. The server will automatically rebuild your app as you make changes. ```shell npx parcel src/index.html ``` -------------------------------- ### Install Tailwind CSS Plugin Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/css.md Install the Tailwind CSS plugin as a development dependency to use it with PostCSS. ```shell yarn add tailwindcss --dev ``` -------------------------------- ### Install Parcel Core and Default Config Source: https://github.com/parcel-bundler/website/blob/v2/src/features/parcel-api.md Install the necessary packages for using the Parcel API. This includes the core Parcel package and a default configuration. ```shell yarn add @parcel/core @parcel/config-default ``` -------------------------------- ### Install Parcel Web Extension Config Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/web-extension.md Install the necessary Parcel configuration for building web extensions as a development dependency. ```shell yarn add @parcel/config-webextension --dev ``` -------------------------------- ### Parcel Configuration Example (.parcelrc) Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/config.html An example of a .parcelrc file showing how to extend the default configuration and specify plugins for various build pipeline stages like transformers, resolvers, namers, packagers, optimizers, compressors, and reporters. ```json { "extends": ["@parcel/config-default"], "transformers": { "*.svg": ["@parcel/transformer-svg-jsx"] }, "resolvers": ["@parcel/resolver-glob", "..."], "namers": ["@company/parcel-namer", "..."], "packagers": { "*.{jpg,png}": "parcel-packager-image-sprite" }, "optimizers": { "*.js": ["parcel-optimizer-license-headers"] }, "compressors": { "*.js": ["...", "@parcel/compressor-gzip"] }, "reporters": ["...", "parcel-reporter-manifest"] } ``` -------------------------------- ### Start Parcel development server with Yarn Source: https://github.com/parcel-bundler/website/blob/v2/src/getting-started/webapp.md Run this command to start the Parcel development server, pointing to your HTML entry file. The server will automatically rebuild your app as you make changes. ```shell yarn parcel src/index.html ``` -------------------------------- ### Packager Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/plugins.html A Packager plugin defines how assets are bundled together into a final output. This example concatenates the code of all assets in a bundle. ```javascript import {Packager} from '@parcel/plugin'; export default new Packager({ async package({bundle}) { let promises = []; bundle.traverseAssets(asset => { promises.push(asset.getCode()); }); let contents = await Promise.all(promises); return { contents: contents.join('\n') }; } }); ``` -------------------------------- ### Setting up Tailwind CSS with PostCSS Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md Install Tailwind CSS and its PostCSS dependencies, then configure `.postcssrc` and `styles.css` to use Tailwind utility classes. ```shell yarn add tailwindcss @tailwindcss/postcss postcss --dev ``` ```json { "plugins": { "tailwindcss": {} } } ``` ```css @import "tailwindcss"; ``` -------------------------------- ### Initialize Parcel with Entry Points Source: https://github.com/parcel-bundler/website/blob/v2/src/features/parcel-api.md Initialize the Parcel bundler with entry points and a default configuration. This is the basic setup for running a build. ```javascript import {Parcel} from '@parcel/core'; let bundler = new Parcel({ entries: 'a.js', defaultConfig: '@parcel/config-default' }); ``` -------------------------------- ### Resolver Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/plugins.html A Resolver plugin customizes how module specifiers are resolved. This example shows how to resolve a 'special-module' to a specific file path and provide its code. ```javascript import {Resolver} from '@parcel/plugin'; import path from 'path'; export default new Resolver({ async resolve({specifier}) { if (specifier === 'special-module') { return { filePath: path.join(__dirname, 'special-module.js'), code: 'export default "This is a special module!";' }; } } }); ``` -------------------------------- ### Namer Plugin Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/scalability/plugins.html A Namer plugin determines the output filename for bundles. This example provides a custom name for image bundles based on their original file path. ```javascript import {Namer} from '@parcel/plugin'; import path from 'path'; export default new Namer({ name({bundle}) { if (bundle.type === 'png' || bundle.type === 'jpg') { let filePath = bundle.getMainEntry().filePath; return `images/${path.basename(filePath)` } } }); ``` -------------------------------- ### Full GraphQL Query with Fragment Imports Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/graphql.md An example of a complete GraphQL query that imports and uses fragments from separate files. ```graphql # import UserFragment from "user.graphql"\n# import "address.graphql"\n\nquery UserQuery($id: ID) {\n user(id: $id) {\n ...UserFragment\n address {\n ...AddressFragment\n }\n }\n} ``` -------------------------------- ### Example Parcel Plugin Package Names Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/authoring-plugins.md Examples of naming conventions for Parcel plugins, distinguishing between official, community, and private packages. Prioritize descriptive names related to the plugin's purpose or the tool it supports. ```bash parcel-transformer-posthtml parcel-packager-wasm parcel-reporter-graph-visualizer ``` ```bash parcel-transformer-es6 (bad) parcel-transformer-babel (good) ``` ```bash parcel-transformer-better-typescript (bad) parcel-transformer-typescript-server (good) ``` -------------------------------- ### Basic Pug Template Example Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/pug.md A standard Pug template demonstrating basic HTML structure, linking stylesheets, and including text content. ```pug doctype html html(lang="en") head link(rel="stylesheet", href="style.css") body h1 Hello Pug! p. Pug is a terse and simple templating language with a strong focus on performance and powerful features. script(type="module", src="index.js") ``` -------------------------------- ### Get All Sources Content Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Retrieves a list of the content for all source files. ```javascript getSourcesContent(): Array ``` -------------------------------- ### Install and Activate Service Worker with Caching Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/javascript.md This example demonstrates how to pre-cache static assets using @parcel/service-worker. It caches all bundles on installation and cleans up old cache versions upon activation. Ensure @parcel/service-worker is installed as a dependency. ```javascript import {manifest, version} from '@parcel/service-worker'; async function install() { const cache = await caches.open(version); await cache.addAll(manifest); } addEventListener('install', e => e.waitUntil(install())); async function activate() { const keys = await caches.keys(); await Promise.all( keys.map(key => key !== version && caches.delete(key)) ); } addEventListener('activate', e => e.waitUntil(activate())); ``` -------------------------------- ### React App Entry Point Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md This JavaScript file sets up the React application by importing necessary functions from react-dom and rendering the main App component into the specified DOM element. ```jsx import { createRoot } from "react-dom/client"; import { App } from "./App"; const container = document.getElementById("app"); const root = createRoot(container) root.render(); ``` -------------------------------- ### Basic TypeScript Example Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/html.md A simple TypeScript file that can be referenced from an HTML file using a script tag. ```js console.log('Hello world!') ``` -------------------------------- ### Extending Parcel Configuration with Dart Transformer Source: https://github.com/parcel-bundler/website/blob/v2/src/blog/alpha1/alpha1.md This example shows how to extend the default Parcel configuration to include a transformer for Dart files. Ensure you have the 'parcel-transform-dart' package installed. ```json { "extends": ["[@parcel/config-default](http://twitter.com/parcel/config-default)"], "transforms": { "*.dart": ["parcel-transform-dart"] } } ``` -------------------------------- ### Optimize Bundle with Source Maps Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/source-maps.md Example of an optimizer plugin that receives and returns source maps. The map is provided as a separate option, not part of the asset. ```javascript import {Optimizer} from '@parcel/plugin'; export default new Optimizer({ // The contents and map are passed separately async optimize({bundle, contents, map}) { return {contents, map}; } }); ``` -------------------------------- ### Import File as ArrayBuffer in JavaScript Source: https://github.com/parcel-bundler/website/blob/v2/src/features/plugins.md Example of importing a file using the 'arraybuffer:' named pipeline in JavaScript to obtain an ArrayBuffer. ```javascript import buffer from 'arraybuffer:./file.png'; ``` -------------------------------- ### Page Component Importing Client Entry and Client Components Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/rsc.md This example shows a server entry point for a Page component. It imports the client entry file and a Client Component, demonstrating how to include client-side logic and interactive components within the server-rendered structure. ```jsx "use server-entry"; import './client'; import {Counter} from './Counter'; export function Page() { return ( {/* ... */} ); } ``` -------------------------------- ### JavaScript API Proxy Configuration Source: https://github.com/parcel-bundler/website/blob/v2/src/features/development.md Configure API proxying using JavaScript in .proxyrc.js or .proxyrc.ts for more complex setups. This example uses http-proxy-middleware to achieve the same result as the JSON configuration. ```javascript const { createProxyMiddleware } = require("http-proxy-middleware"); module.exports = function (app) { app.use( "/api", createProxyMiddleware({ target: "http://localhost:8000/", pathRewrite: { "^/api": "", }, }) ); }; ``` -------------------------------- ### Parcel 1: Hooking into Bundle Events Source: https://github.com/parcel-bundler/website/blob/v2/src/migration/parcel-1.md In Parcel 1, you could listen for build events like 'buildEnd' and 'buildError' using the bundler instance's .on() method. This example shows the basic setup for Parcel 1. ```javascript import Bundler from "parcel-bundler" const bundler = new Bundler({ /* ... */ }) bundler.bundle() bundler.on("buildEnd", () => { /* ... */ }) bundler.on("buildError", (error) => { /* ... */ }) ``` -------------------------------- ### Configure PostHTML with .posthtmlrc for Doctype Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/html.md Configure PostHTML using a `.posthtmlrc` file to set the doctype. This example specifies 'HTML 5' as the doctype. ```json { "plugins": { "posthtml-doctype": { "doctype": "HTML 5" } } } ``` -------------------------------- ### Configure PostCSS with Tailwind CSS Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/css.md Create a .postcssrc file to specify PostCSS plugins and their options. This example configures Tailwind CSS. ```json { "plugins": { "tailwindcss": true } } ``` -------------------------------- ### Install Parcel with npm Source: https://github.com/parcel-bundler/website/blob/v2/src/getting-started/webapp.md Install Parcel as a development dependency in your project using npm. ```shell npm install --save-dev parcel ``` -------------------------------- ### CSS with Custom Media Query Substitution Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/css.md Example showing how custom media queries are defined and used, which Parcel CSS substitutes ahead of time. ```css @custom-media --modern (color), (hover); @media (--modern) and (width > 1024px) { .a { color: green; } } ``` -------------------------------- ### Install Parcel with Yarn Source: https://github.com/parcel-bundler/website/blob/v2/src/getting-started/webapp.md Install Parcel as a development dependency in your project using Yarn. ```shell yarn add --dev parcel ``` -------------------------------- ### Instantiate and Add Source Maps from Buffers Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/source-maps.md Shows how to create a SourceMap instance from a buffer, or add a buffer to an existing SourceMap. Also demonstrates adding another SourceMap object to the current one. ```javascript // Source maps can be serialized to buffers, which is what we use for caching in Parcel. // You can instantiate a SourceMap with these buffer values by passing it to the constructor let map = new SourceMap(projectRoot, mapBuffer); // You can also add a buffer to an existing source map using the addBuffer method. sourcemap.addBuffer(originalMapBuffer, lineOffset); // One SourceMap object may be added to another using the addSourceMap method. sourcemap.addSourceMap(map, lineOffset); ``` -------------------------------- ### Build a single entry point Source: https://github.com/parcel-bundler/website/blob/v2/src/features/cli.md Use the `parcel build` command followed by the path to your HTML entry file to perform a production build. ```bash parcel build src/index.html ``` -------------------------------- ### Configure Reporter Plugins Source: https://github.com/parcel-bundler/website/blob/v2/src/features/plugins.md Configure reporter plugins to receive build events. This example adds the bundle analyzer reporter and extends the default reporters using '...'. ```json { "extends": "@parcel/config-default", "reporters": ["...", "@parcel/reporter-bundle-analyzer"] } ``` -------------------------------- ### Install TypeScript Definitions for React Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md Install the necessary development dependencies for TypeScript definitions when using React with Parcel. ```shell yarn add @types/react @types/react-dom --dev ``` -------------------------------- ### Transformer API Example Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/transformer.md An example of a basic transformer plugin. This snippet demonstrates how to define a transformer that can process and modify code. ```javascript import { Transformer } from '@parcel/plugin'; export default new Transformer({ async transform({ asset, // options, // logger, // env, // config, /// }) { // asset.isASTDirty ? asset.getAST() : asset.getCode(); // asset.setAST(ast); // asset.setCode(code); // asset.addDependency(dep); // asset.invalidateOnFileChange(filePath); // asset.setMap(map); return [asset]; }, }); ``` -------------------------------- ### Install Dependencies for RSC Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/rsc.md Install the necessary React and Parcel RSC packages. Ensure you are using React and ReactDOM v19.1.0 or later. ```bash npm install react react-dom @parcel/rsc ``` -------------------------------- ### Build Breakdown by Phase Source: https://github.com/parcel-bundler/website/blob/v2/src/features/profiling.md Use this query to get a high-level breakdown of your build by main phases like building, bundling, and packaging. It helps identify if any particular phase is taking longer than expected. ```sql select name, SUM(CAST(dur AS double)/1000/1000) as dur_ms from slice s where s.category = "Core" group by name order by dur_ms desc ``` -------------------------------- ### Install SVG to JSX Transformer Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/react.md Install the @parcel/transformer-svg-jsx plugin to enable importing SVGs as React components. Add it to your .parcelrc configuration. ```shell yarn add @parcel/transformer-svg-jsx --dev ``` -------------------------------- ### Install Parcel Default Config and TSC Transformer Source: https://github.com/parcel-bundler/website/blob/v2/src/migration/parcel-1.md Install the default Parcel configuration and the TSC transformer for TypeScript compilation in Parcel 2. ```shell yarn add @parcel/config-default @parcel/transformer-typescript-tsc --dev ``` -------------------------------- ### Configure package.json for a Library Source: https://github.com/parcel-bundler/website/blob/v2/src/getting-started/library.md Set up the package.json file for a library, specifying the source file and the main output target. ```json { "name": "my-library", "version": "1.0.0", "source": "src/index.js", "main": "dist/main.js", "devDependencies": { "parcel": "latest" } } ``` -------------------------------- ### Configure Library Build Outputs Source: https://github.com/parcel-bundler/website/blob/v2/src/features/targets.md Set up standard library build outputs including 'main' (CommonJS), 'module' (ES module), and 'types' using top-level fields in `package.json`. ```json { "name": "my-library", "version": "1.0.0", "source": "src/index.js", "main": "dist/main.js", "module": "dist/module.js", "types": "dist/types.d.ts" } ``` -------------------------------- ### Install Parcel transformers for raw asset handling Source: https://github.com/parcel-bundler/website/blob/v2/src/migration/parcel-1.md Install necessary Parcel transformers to handle raw asset types like zip and tgz. ```shell yarn add @parcel/config-default @parcel/transformer-raw --dev ``` -------------------------------- ### Extend Default Configuration with Pipeline Extension Source: https://github.com/parcel-bundler/website/blob/v2/src/features/plugins.md This example shows how to extend the default configuration and use the '...' syntax to insert a custom transformer into the SVG pipeline. ```json { "extends": "@parcel/config-default", "transformers": { "icons/*.svg": ["@company/parcel-transformer-svg-icons", "..."] } } ``` -------------------------------- ### Adding Hints and Documentation URLs to Diagnostics Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/logging.md Enhance diagnostics with actionable `hints` for users and a `documentationURL` for further information. ```javascript throw new ThrowableDiagnostic({ diagnostic: { message: 'Could not find a config file', hints: ['Create a tool.config.json file in the project root.'], documentationURL: 'http://example.com/' } }); ``` -------------------------------- ### Image Optimization with Query Parameters Source: https://github.com/parcel-bundler/website/blob/v2/src/features/production.md Reference images in HTML using query parameters to specify format and size for optimization. This example shows how to request WebP and JPEG versions at different resolutions. ```html ``` -------------------------------- ### Example Atom Feed Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/xml.md This example demonstrates an Atom feed with a single entry. Parcel rewrites URL references in elements and processes images within the content. ```xml Example Feed A subtitle. urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6 2021-12-13T18:30:02Z Awesome post urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2021-12-13T18:30:02Z Some text.

This is the entry content.

John Doe johndoe@example.com
``` -------------------------------- ### Import All Fragments from a File Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/graphql.md Demonstrates how to import all fragments defined in a 'fragments.graphql' file into another GraphQL file. ```graphql # import "fragments.graphql"\n# import * from "fragments.graphql" ``` -------------------------------- ### Example: Reading a file with cache invalidation Source: https://github.com/parcel-bundler/website/blob/v2/src/features/macros.md Demonstrates how to use `invalidateOnFileChange` to recompile the calling code when a specific file changes. This example recompiles `index.ts` when `message.txt` is edited. ```tsx import {readFile} from './macro.ts' with {type: 'macro'}; console.log(readFile('message.txt')) ``` ```ts import type {MacroContext} from '@parcel/macros'; import fs from 'fs'; export async function readFile(this: MacroContext | void, filePath: string) { this?.invalidateOnFileChange(filePath); return fs.readFileSync(filePath, 'utf8'); } ``` ```text hello world! ``` -------------------------------- ### Specify Multiple HTML Entries via CLI Source: https://github.com/parcel-bundler/website/blob/v2/src/features/targets.md Use this to build multiple HTML files simultaneously from the command line. ```shell parcel src/a.html src/b.html ``` -------------------------------- ### Parcel Web Extension Development Script Source: https://github.com/parcel-bundler/website/blob/v2/src/recipes/web-extension.md Configure Parcel for development builds of web extensions, enabling HMR and hot reloading. Use this script with `yarn start` or `npm start`. ```json { "scripts": { "start": "parcel watch src/manifest.json --host localhost --config @parcel/config-webextension", "build": "parcel build src/manifest.json --config @parcel/config-webextension" } } ``` -------------------------------- ### Basic Vue.js App Setup Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/vue.md Demonstrates the basic HTML, JavaScript, and Vue component structure for a simple Vue.js application managed by Parcel. Ensure you are using Vue 3 or later. ```html
``` ```jsx import { createApp } from "vue"; import App from "./App.vue"; const app = createApp(App); app.mount("#app"); ``` ```html ``` -------------------------------- ### Enable Lazy Mode for Development Source: https://github.com/parcel-bundler/website/blob/v2/src/features/development.md Use the `--lazy` flag to defer file builds until they are requested by the browser. This significantly speeds up initial server startup, especially for large applications. ```shell parcel 'pages/*.html' --lazy ``` -------------------------------- ### Import GLSL Shader with Dependencies Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/glsl.md Demonstrates importing a GLSL fragment shader that includes dependencies from other local GLSL files and from node_modules using `#pragma glslify`. This allows for modular shader development and reuse of libraries. ```javascript import frag from './shader.frag'; // ... gl.shaderSource(..., frag); // ... ``` ```glsl // import a function from another file #pragma glslify: calc_frag_color = require('./lib.glsl') precision mediump float; varying vec3 vpos; void main() { gl_FragColor = calc_frag_color(vpos); } ``` ```glsl // import a function from node_modules #pragma glslify: noise = require('glsl-noise/simplex/3d') vec4 calc_frag_color(vec3 pos) { return vec4(vec3(noise(pos * 25.0)), 1.0); } // export a function #pragma glslify: export(calc_frag_color) ``` -------------------------------- ### Terminal Build Error Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/dx/diagnostics.html This is an example of a build error shown in the terminal by Parcel. It includes the error message, file path, line number, and a code frame highlighting the issue. ```bash $ parcel index.html Server running at http://localhost:1234 🚨 Build failed. @parcel/core: Cannot resolve 'ract' from './index.js' /dev/app/index.js:1:19 > 1 | import React from 'ract'; > | ^^^^^^ 2 | 3 | function Test() { @parcel/resolver-default: Cannot find module 'ract' Did you mean 'react'? ``` -------------------------------- ### Importing and Logging with Side Effects Source: https://github.com/parcel-bundler/website/blob/v2/src/features/scope-hoisting.md This example demonstrates importing a function and logging its result. It is used in conjunction with `package.json` to illustrate side effect handling. ```javascript import {add} from 'math'; console.log(add(2, 3)); ``` -------------------------------- ### Basic Elm App Setup Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/elm.md This snippet shows how to set up a basic Elm application that can be imported and run within a Parcel project. It includes the HTML structure, the JavaScript import, and the Elm code for a simple counter. ```html
``` ```javascript import { Elm } from "./Main.elm"; Elm.Main.init({ node: document.getElementById("root") }); ``` ```elm module Main exposing (..) import Browser import Html exposing (Html, button, div, text) import Html.Events exposing (onClick) main = Browser.sandbox { init = init, update = update, view = view } type alias Model = Int init : Model init = 0 type Msg = Increment | Decrement update : Msg -> Model -> Model update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 view : Model -> Html Msg view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] ] ``` -------------------------------- ### Create a new React Server Components project Source: https://github.com/parcel-bundler/website/blob/v2/src/blog/v2-14-0/v2-14-0.md Use the `create-parcel` CLI to scaffold a new project from a template. This command initializes a Git repository, sets up boilerplate files, and installs dependencies. ```bash npm create parcel react-server my-rsc-app ``` -------------------------------- ### BuildStartEvent Type Source: https://github.com/parcel-bundler/website/blob/v2/api/reporter.html An event signaling that the Parcel build process has just started. ```javascript type BuildStartEvent = {| +type: 'buildStart', |} ``` -------------------------------- ### Add Indexed and VLQ Mappings to SourceMap Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/source-maps.md Demonstrates how to create a SourceMap instance and add both indexed and VLQ mappings. Optional line and column offsets can be provided to adjust the generated mappings. ```javascript import SourceMap from '@parcel/source-map'; let sourcemap = new SourceMap(projectRoot); // Each function that adds mappings has optional offset arguments. // These can be used to offset the generated mappings by a certain amount. let lineOffset = 0; let columnOffset = 0; // Add indexed mappings // These are mappings that can sometimes be extracted from a library even before they get converted into VLQ Mappings sourcemap.addIndexedMappings( [ { generated: { // line index starts at 1 line: 1, // column index starts at 0 column: 4, }, original: { // line index starts at 1 line: 1, // column index starts at 0 column: 4, }, source: "index.js", // Name is optional name: "A", }, ], lineOffset, columnOffset ); // Add vlq mappings. This is what would be outputted into a vlq encoded source map sourcemap.addVLQMap( { file: "min.js", names: ["bar", "baz", "n"], sources: ["one.js", "two.js"], sourceRoot: "/the/root", mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA", }, lineOffset, columnOffset ); ``` -------------------------------- ### Get All Names Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Retrieves a list of all unique names used in the source map. ```javascript getNames(): Array ``` -------------------------------- ### getSource Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Get the source file filepath for a certain index of the sources array. ```APIDOC ## getSource(index: number): string ### Description Get the source file filepath for a certain index of the sources array. ### Parameters * **`index`** (number) - Required - The index of the source in the sources array. ### Returns * (string) - The filepath of the source file. ``` -------------------------------- ### getSourceIndex Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Get the index in the sources array for a certain source file filepath. ```APIDOC ## getSourceIndex(source: string): number ### Description Get the index in the sources array for a certain source file filepath. ### Parameters * **`source`** (string) - Required - The filepath of the source file. ### Returns * (number) - The index of the source file in the sources array, or -1 if not found. ``` -------------------------------- ### Running Parcel with Pug Entry Point Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/pug.md Use this command to build a project with Pug as the main entry point. ```shell parcel index.pug ``` -------------------------------- ### WatchStartEvent Type Source: https://github.com/parcel-bundler/website/blob/v2/api/reporter.html An event signaling that the Parcel build process has started in watch mode. ```javascript type WatchStartEvent = {| +type: 'watchStart', |} ``` -------------------------------- ### JSX Component Example Source: https://github.com/parcel-bundler/website/blob/v2/src/home/targets/transpilation.html A simple React component written using JSX syntax. ```jsx function DogName(props) { return ( {props.dog?.name ?? 'Buddy'} ); } ``` -------------------------------- ### Log a Warning with Code Frame and Hints Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/logging.md Example of logging a warning message using the logger. This includes a code frame for specific code location, hints for the user, and a URL to documentation. This is useful for non-critical issues that require user attention and guidance. ```javascript import {Transformer} from '@parcel/plugin'; export default new Transformer({ async transform({asset, logger}) { // ... logger.warn({ message: 'This feature is deprecated.', codeFrames: [{ filePath: asset.filePath, code: await asset.getCode(), codeHighlights: [{ start: { line: 1, column: 5 }, end: { line: 1, column: 10 } }] }], hints: ['Please use this other feature instead.'], documentationURL: 'http://example.com/' }); }, }); ``` -------------------------------- ### Configure Pseudo Class Replacement in package.json Source: https://github.com/parcel-bundler/website/blob/v2/src/languages/css.md Set up pseudo-class mappings in package.json to replace CSS pseudo classes with normal classes, enabling polyfilling for older browsers. ```json { "@parcel/transformer-css": { "pseudoClasses": { "focusVisible": "focus-visible" } } } ``` -------------------------------- ### Get All Sources Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Retrieves a list of all source file paths associated with the source map. ```javascript getSources(): Array ``` -------------------------------- ### Offset Mapping Lines Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Adjusts the line numbers of mappings relative to a given starting line. ```javascript offsetLines(line: number, lineOffset: number): ?IndexedMapping ``` -------------------------------- ### Handle Build Failure Event Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/reporter.md This snippet shows how to create a reporter plugin that listens for the 'buildFailure' event and logs the number of errors to standard output. ```javascript import {Reporter} from '@parcel/plugin'; export default new Reporter({ report({event}) { if (event.type === 'buildFailure') { process.stdout.write(`🚨 Build failed with ${event.diagnostics.length} errors.\n`); } } }); ``` -------------------------------- ### Configure Yarn/NPM Workspaces Source: https://github.com/parcel-bundler/website/blob/v2/src/features/plugins.md Set up a monorepo structure using Yarn or NPM workspaces. Reference local packages in the root package.json to manage local plugins. ```json { "name": "my-project", "private": true, "workspaces": ["packages/*"] } ``` -------------------------------- ### Get Name by Index Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Retrieves the name string corresponding to a given index in the names array. ```javascript getName(index: number): string ``` -------------------------------- ### Get Source Content Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Retrieves the content of a specific source file if it has been inlined into the source map. ```javascript getSourceContent(sourceName: string): string | null ``` -------------------------------- ### Handle Build Progress Events Source: https://github.com/parcel-bundler/website/blob/v2/src/plugin-system/reporter.md Implement a reporter to log build progress events. This snippet shows how to process different phases of the build, such as transforming, resolving, bundling, packaging, and optimizing, by writing messages to standard output. ```javascript import {Reporter} from '@parcel/plugin'; export default new Reporter({ report({event}) { if (event.type === 'buildProgress') { switch (event.phase) { case 'transforming': process.stdout.write(`Transforming ${event.filePath}... `); break; case 'resolving': process.stdout.write(`Resolving ${event.dependency.specifier}... `); break; case 'bundling': process.stdout.write('Bundling...\n'); break; case 'packaging': process.stdout.write(`Packaging ${event.bundle.displayName}... `); break; case 'optimizing': process.stdout.write(`Optimizing ${event.bundle.displayName}... `); break; } } } }); ``` -------------------------------- ### Offset Mapping Columns Source: https://github.com/parcel-bundler/website/blob/v2/api/source-map.html Adjusts the column numbers of mappings relative to a given starting line and column. ```javascript offsetColumns(line: number, column: number, columnOffset: number): ?IndexedMapping ```