parcel-bundler

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Parcel Bundler

Parcel 打包工具

You are an expert in Parcel, the zero-configuration build tool for the web. Follow these guidelines when working with Parcel projects.
您是Web零配置构建工具Parcel的专家。在处理Parcel项目时,请遵循以下指南。

Core Principles

核心原则

  • Zero configuration by default - Parcel works out of the box
  • Automatic dependency detection and installation
  • Built-in development server with hot module replacement
  • Native performance with Rust-based compiler
  • Automatic code splitting and optimization
  • 默认零配置 - Parcel开箱即用
  • 自动检测并安装依赖
  • 内置支持热模块替换的开发服务器
  • 基于Rust编译器的原生性能
  • 自动代码分割与优化

Project Structure

项目结构

project/
├── src/
│   ├── index.html        # HTML entry point
│   ├── index.js          # JavaScript entry
│   ├── styles.css        # Stylesheets
│   └── assets/           # Images, fonts, etc.
├── dist/                 # Build output (auto-generated)
├── .parcelrc             # Optional configuration
└── package.json
project/
├── src/
│   ├── index.html        # HTML entry point
│   ├── index.js          # JavaScript entry
│   ├── styles.css        # Stylesheets
│   └── assets/           # Images, fonts, etc.
├── dist/                 # Build output (auto-generated)
├── .parcelrc             # Optional configuration
└── package.json

Getting Started

快速入门

Basic Usage

基础用法

bash
undefined
bash
undefined

Development with hot reload

带热重载的开发模式

parcel src/index.html
parcel src/index.html

Production build

生产构建

parcel build src/index.html
undefined
parcel build src/index.html
undefined

Package.json Scripts

Package.json 脚本

json
{
  "scripts": {
    "dev": "parcel src/index.html",
    "build": "parcel build src/index.html",
    "clean": "rm -rf dist .parcel-cache"
  },
  "source": "src/index.html"
}
json
{
  "scripts": {
    "dev": "parcel src/index.html",
    "build": "parcel build src/index.html",
    "clean": "rm -rf dist .parcel-cache"
  },
  "source": "src/index.html"
}

Entry Points

入口文件

HTML Entry

HTML入口

html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="./styles.css">
</head>
<body>
  <div id="app"></div>
  <script type="module" src="./index.js"></script>
</body>
</html>
html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="./styles.css">
</head>
<body>
  <div id="app"></div>
  <script type="module" src="./index.js"></script>
</body>
</html>

JavaScript Entry

JavaScript入口

bash
parcel build src/index.js --dist-dir lib
bash
parcel build src/index.js --dist-dir lib

Multiple Entry Points

多入口文件

bash
parcel build src/index.html src/admin.html
bash
parcel build src/index.html src/admin.html

Supported Languages and File Types

支持的语言与文件类型

Parcel supports out of the box:
  • JavaScript/TypeScript:
    .js
    ,
    .jsx
    ,
    .ts
    ,
    .tsx
    ,
    .mjs
  • Styles:
    .css
    ,
    .scss
    ,
    .sass
    ,
    .less
    ,
    .styl
  • HTML:
    .html
    ,
    .htm
  • Images:
    .png
    ,
    .jpg
    ,
    .gif
    ,
    .svg
    ,
    .webp
  • Fonts:
    .woff
    ,
    .woff2
    ,
    .ttf
    ,
    .otf
    ,
    .eot
  • Data:
    .json
    ,
    .yaml
    ,
    .toml
    ,
    .xml
  • WebAssembly:
    .wasm
Parcel开箱即支持:
  • JavaScript/TypeScript:
    .js
    ,
    .jsx
    ,
    .ts
    ,
    .tsx
    ,
    .mjs
  • 样式文件:
    .css
    ,
    .scss
    ,
    .sass
    ,
    .less
    ,
    .styl
  • HTML文件:
    .html
    ,
    .htm
  • 图片文件:
    .png
    ,
    .jpg
    ,
    .gif
    ,
    .svg
    ,
    .webp
  • 字体文件:
    .woff
    ,
    .woff2
    ,
    .ttf
    ,
    .otf
    ,
    .eot
  • 数据文件:
    .json
    ,
    .yaml
    ,
    .toml
    ,
    .xml
  • WebAssembly:
    .wasm

Configuration (When Needed)

配置(必要时)

.parcelrc

.parcelrc

json
{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.svg": ["@parcel/transformer-svg-react"]
  },
  "reporters": ["...", "parcel-reporter-bundle-analyzer"]
}
json
{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.svg": ["@parcel/transformer-svg-react"]
  },
  "reporters": ["...", "parcel-reporter-bundle-analyzer"]
}

package.json Targets

package.json 目标配置

json
{
  "targets": {
    "main": {
      "source": "src/index.js",
      "distDir": "dist",
      "context": "browser",
      "outputFormat": "esm"
    }
  }
}
json
{
  "targets": {
    "main": {
      "source": "src/index.js",
      "distDir": "dist",
      "context": "browser",
      "outputFormat": "esm"
    }
  }
}

TypeScript Support

TypeScript 支持

Automatic Configuration

自动配置

Parcel handles TypeScript automatically. Just use
.ts
or
.tsx
files.
Parcel会自动处理TypeScript,只需使用
.ts
.tsx
文件即可。

tsconfig.json

tsconfig.json

json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "isolatedModules": true
  }
}
json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "isolatedModules": true
  }
}

React Support

React 支持

Automatic JSX

自动处理JSX

jsx
// Parcel handles JSX automatically
import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
jsx
// Parcel自动处理JSX
import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

CSS and Styling

CSS与样式处理

CSS Imports

CSS导入

javascript
import './styles.css';
javascript
import './styles.css';

CSS Modules

CSS Modules

javascript
import * as styles from './Button.module.css';

function Button() {
  return <button className={styles.primary}>Click me</button>;
}
javascript
import * as styles from './Button.module.css';

function Button() {
  return <button className={styles.primary}>Click me</button>;
}

Sass/SCSS

Sass/SCSS

javascript
import './styles.scss';
Parcel installs
sass
automatically when you use
.scss
files.
javascript
import './styles.scss';
当您使用
.scss
文件时,Parcel会自动安装
sass

Asset Handling

资源处理

Importing Assets

导入资源

javascript
import logo from './logo.png';
import data from './data.json';

// Use in JSX
<img src={logo} alt="Logo" />
javascript
import logo from './logo.png';
import data from './data.json';

// 在JSX中使用
<img src={logo} alt="Logo" />

URL References

URL引用

javascript
const imageUrl = new URL('./image.png', import.meta.url);
javascript
const imageUrl = new URL('./image.png', import.meta.url);

Code Splitting

代码分割

Dynamic Imports

动态导入

javascript
// Automatic code splitting
const LazyComponent = React.lazy(() => import('./LazyComponent'));

// Or manual
async function loadModule() {
  const module = await import('./heavy-module.js');
  return module.default;
}
javascript
// 自动代码分割
const LazyComponent = React.lazy(() => import('./LazyComponent'));

// 或手动分割
async function loadModule() {
  const module = await import('./heavy-module.js');
  return module.default;
}

Shared Bundles

共享打包文件

Parcel automatically creates shared bundles for code used across multiple entry points.
Parcel会自动为多入口文件共享的代码创建共享打包文件。

Environment Variables

环境变量

.env Files

.env 文件

undefined
undefined

.env

.env

undefined
undefined

.env.production

.env.production

undefined
undefined

Usage in Code

代码中使用

javascript
const apiUrl = process.env.API_URL;
javascript
const apiUrl = process.env.API_URL;

Defining in package.json

在package.json中定义

json
{
  "targets": {
    "default": {
      "publicUrl": "/my-app/"
    }
  }
}
json
{
  "targets": {
    "default": {
      "publicUrl": "/my-app/"
    }
  }
}

Development Server

开发服务器

Default Configuration

默认配置

bash
parcel src/index.html
bash
parcel src/index.html
undefined
undefined

Custom Port

自定义端口

bash
parcel src/index.html --port 3000
bash
parcel src/index.html --port 3000

HTTPS

HTTPS配置

bash
parcel src/index.html --https
bash
parcel src/index.html --https

Proxy API Requests

代理API请求

json
{
  "devServer": {
    "proxy": {
      "/api": {
        "target": "http://localhost:8080"
      }
    }
  }
}
json
{
  "devServer": {
    "proxy": {
      "/api": {
        "target": "http://localhost:8080"
      }
    }
  }
}

Production Build

生产构建

Basic Build

基础构建

bash
parcel build src/index.html
bash
parcel build src/index.html

Output Configuration

输出配置

bash
parcel build src/index.html --dist-dir build --public-url /app/
bash
parcel build src/index.html --dist-dir build --public-url /app/

No Source Maps

禁用Source Maps

bash
parcel build src/index.html --no-source-maps
bash
parcel build src/index.html --no-source-maps

Optimization

优化

Automatic Optimizations

自动优化

Parcel automatically:
  • Minifies JavaScript, CSS, HTML, and SVG
  • Compresses images
  • Generates content hashes for caching
  • Tree-shakes unused code
  • Scope hoists modules
Parcel会自动执行以下操作:
  • 压缩JavaScript、CSS、HTML与SVG
  • 压缩图片
  • 生成内容哈希用于缓存
  • 摇树优化移除未使用代码
  • 作用域提升模块

Bundle Analysis

打包文件分析

bash
npm install -D parcel-reporter-bundle-analyzer
bash
npm install -D parcel-reporter-bundle-analyzer

Add to .parcelrc

添加到 .parcelrc

{ "extends": "@parcel/config-default", "reporters": ["...", "parcel-reporter-bundle-analyzer"] }
undefined
{ "extends": "@parcel/config-default", "reporters": ["...", "parcel-reporter-bundle-analyzer"] }
undefined

Caching

缓存

Parcel uses aggressive caching:
bash
undefined
Parcel使用高效缓存:
bash
undefined

Clear cache

清除缓存

rm -rf .parcel-cache
rm -rf .parcel-cache

Or

parcel build --no-cache
undefined
parcel build --no-cache
undefined

Plugin Development

插件开发

Plugin Types

插件类型

  • Transformers: Transform source files
  • Resolvers: Custom module resolution
  • Bundlers: Custom bundling logic
  • Namers: Custom output naming
  • Packagers: Package bundles
  • Optimizers: Optimize bundles
  • Reporters: Custom build reporting
  • Transformers(转换器):转换源文件
  • Resolvers(解析器):自定义模块解析逻辑
  • Bundlers(打包器):自定义打包逻辑
  • Namers(命名器):自定义输出命名
  • Packagers(打包工具):打包文件
  • Optimizers(优化器):优化打包文件
  • Reporters(报告器):自定义构建报告

Plugin Rules

插件规则

  1. Stateless: Avoid internal state
  2. Pure: Same input produces same output
  3. No side effects: Don't modify external state
  1. 无状态:避免内部状态
  2. 纯函数:相同输入产生相同输出
  3. 无副作用:不要修改外部状态

Library Development

库开发

Package.json Configuration

Package.json 配置

json
{
  "name": "my-library",
  "source": "src/index.ts",
  "main": "dist/main.js",
  "module": "dist/module.js",
  "types": "dist/types.d.ts",
  "targets": {
    "main": {
      "outputFormat": "commonjs"
    },
    "module": {
      "outputFormat": "esmodule"
    },
    "types": {
      "source": "src/index.ts"
    }
  }
}
json
{
  "name": "my-library",
  "source": "src/index.ts",
  "main": "dist/main.js",
  "module": "dist/module.js",
  "types": "dist/types.d.ts",
  "targets": {
    "main": {
      "outputFormat": "commonjs"
    },
    "module": {
      "outputFormat": "esmodule"
    },
    "types": {
      "source": "src/index.ts"
    }
  }
}

Best Practices

最佳实践

Do

建议做法

  • Start with zero configuration
  • Let Parcel handle asset optimization
  • Use dynamic imports for code splitting
  • Leverage automatic dependency installation
  • Use CSS Modules for component styles
  • 从无配置开始
  • 让Parcel处理资源优化
  • 使用动态导入进行代码分割
  • 利用自动依赖安装功能
  • 使用CSS Modules管理组件样式

Avoid

避免做法

  • Over-configuring when defaults work
  • Fighting against Parcel's conventions
  • Manually optimizing what Parcel handles
  • Ignoring build warnings and errors
  • 在默认配置可用时过度配置
  • 违背Parcel的约定
  • 手动优化Parcel已处理的内容
  • 忽略构建警告与错误

Common Patterns

常见模式

Single Page Application

单页应用

html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My App</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="./index.tsx"></script>
</body>
</html>
html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My App</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="./index.tsx"></script>
</body>
</html>

Static Site

静态站点

bash
parcel build src/*.html
bash
parcel build src/*.html

Web Worker

Web Worker

javascript
const worker = new Worker(new URL('./worker.js', import.meta.url), {
  type: 'module'
});
javascript
const worker = new Worker(new URL('./worker.js', import.meta.url), {
  type: 'module'
});

Troubleshooting

问题排查

Clear Cache

清除缓存

bash
rm -rf .parcel-cache dist
bash
rm -rf .parcel-cache dist

Verbose Output

详细输出

bash
parcel build --log-level verbose
bash
parcel build --log-level verbose

Debug Mode

调试模式

bash
DEBUG=parcel:* parcel build
bash
DEBUG=parcel:* parcel build

Migration from Other Bundlers

从其他打包工具迁移

  • Remove webpack.config.js or similar
  • Remove loader/plugin dependencies
  • Update import statements if needed
  • Parcel will auto-install required dependencies
  • 移除webpack.config.js或类似配置文件
  • 移除加载器/插件依赖
  • 必要时更新导入语句
  • Parcel会自动安装所需依赖