parcel-bundler
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseParcel 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.jsonproject/
├── 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.jsonGetting Started
快速入门
Basic Usage
基础用法
bash
undefinedbash
undefinedDevelopment with hot reload
带热重载的开发模式
parcel src/index.html
parcel src/index.html
Production build
生产构建
parcel build src/index.html
undefinedparcel build src/index.html
undefinedPackage.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 libbash
parcel build src/index.js --dist-dir libMultiple Entry Points
多入口文件
bash
parcel build src/index.html src/admin.htmlbash
parcel build src/index.html src/admin.htmlSupported 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 or files.
.ts.tsxParcel会自动处理TypeScript,只需使用或文件即可。
.ts.tsxtsconfig.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 automatically when you use files.
sass.scssjavascript
import './styles.scss';当您使用文件时,Parcel会自动安装。
.scsssassAsset 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 文件
undefinedundefined.env
.env
API_URL=https://api.example.com
undefinedAPI_URL=https://api.example.com
undefined.env.production
.env.production
API_URL=https://api.production.com
undefinedAPI_URL=https://api.production.com
undefinedUsage 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.htmlbash
parcel src/index.htmlServes at http://localhost:1234
在 http://localhost:1234 启动服务
undefinedundefinedCustom Port
自定义端口
bash
parcel src/index.html --port 3000bash
parcel src/index.html --port 3000HTTPS
HTTPS配置
bash
parcel src/index.html --httpsbash
parcel src/index.html --httpsProxy 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.htmlbash
parcel build src/index.htmlOutput 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-mapsbash
parcel build src/index.html --no-source-mapsOptimization
优化
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-analyzerbash
npm install -D parcel-reporter-bundle-analyzerAdd to .parcelrc
添加到 .parcelrc
{
"extends": "@parcel/config-default",
"reporters": ["...", "parcel-reporter-bundle-analyzer"]
}
undefined{
"extends": "@parcel/config-default",
"reporters": ["...", "parcel-reporter-bundle-analyzer"]
}
undefinedCaching
缓存
Parcel uses aggressive caching:
bash
undefinedParcel使用高效缓存:
bash
undefinedClear cache
清除缓存
rm -rf .parcel-cache
rm -rf .parcel-cache
Or
或
parcel build --no-cache
undefinedparcel build --no-cache
undefinedPlugin 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
插件规则
- Stateless: Avoid internal state
- Pure: Same input produces same output
- No side effects: Don't modify external state
- 无状态:避免内部状态
- 纯函数:相同输入产生相同输出
- 无副作用:不要修改外部状态
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/*.htmlbash
parcel build src/*.htmlWeb 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 distbash
rm -rf .parcel-cache distVerbose Output
详细输出
bash
parcel build --log-level verbosebash
parcel build --log-level verboseDebug Mode
调试模式
bash
DEBUG=parcel:* parcel buildbash
DEBUG=parcel:* parcel buildMigration 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会自动安装所需依赖