Parzelle Cheatsheet¶
- Das Zero Configuration Build Tool
Parcel ist ein Web-Anwendungsbündelr, differenziert durch seine Entwicklererfahrung. Es bietet schnelle Leistung mit Multicore-Verarbeitung und erfordert Null-Konfiguration. < p>
Inhaltsverzeichnis¶
- [Installation](#installation
- (#getting-started)
- [Projektstruktur](#project-structure_
- (#development-server_)
- (#building-for-production_)
- (#asset-types)
- Transformationen
- [Code Splitting](#code-splitting_
- (#hot-module-replacement_)
- Umweltvariablen
- Plugins
- Konfiguration
- [Optimierung](LINK_12__
- Targets
- (#caching_)
- Quelle Maps
- [Bundle Analysis](LINK_16__
- [Migration](LINK_17__
- Beste Praktiken
Installation¶
Globale Installation¶
# Install Parcel globally
npm install -g parcel
# Or with Yarn
yarn global add parcel
# Check version
parcel --version
```_
### Lokale Installation (empfohlen)
```bash
# Initialize npm project
npm init -y
# Install Parcel as dev dependency
npm install --save-dev parcel
# Or with Yarn
yarn add --dev parcel
```_
### Paket.json Scripts
```json
{
"scripts": {
"start": "parcel src/index.html",
"dev": "parcel src/index.html --open",
"build": "parcel build src/index.html",
"clean": "rm -rf dist .parcel-cache"
}
}
```_
## Erste Schritte
### Grundlegende HTML Eingangsstelle
```html
<!-- src/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Parcel App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./index.js"></script>
</body>
</html>
```_
### Grundlegendes JavaScript Eintragung
```javascript
// src/index.js
import './styles.css';
console.log('Hello from Parcel!');
// Import and use a module
import { greet } from './utils';
greet('World');
```_
### Basis CSS
```css
/* src/styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
```_
### Run Development Server
```bash
# Start development server
npm start
# Or with specific port
parcel src/index.html --port 3000
# Open browser automatically
parcel src/index.html --open
```_
## Projektstruktur
### Typisches Paketprojekt
```bash
my-parcel-app/
├── src/
│ ├── index.html
│ ├── index.js
│ ├── styles.css
│ ├── components/
│ │ ├── Header.js
│ │ └── Footer.js
│ ├── assets/
│ │ ├── images/
│ │ └── fonts/
│ └── utils/
│ └── helpers.js
├── dist/ # Build output
├── .parcel-cache/ # Parcel cache
├── package.json
└── .gitignore
```_
### Mehrere Entry Points
```json
{
"scripts": {
"start": "parcel src/*.html",
"build": "parcel build src/*.html"
}
}
```_
### Bibliothek Projektstruktur
```bash
my-library/
├── src/
│ ├── index.js
│ ├── components/
│ └── utils/
├── package.json
└── .parcelrc
```_
## Entwicklungsserver
### Basis-Entwicklungsserver
```bash
# Start dev server
parcel src/index.html
# Custom port
parcel src/index.html --port 8080
# Custom host
parcel src/index.html --host 0.0.0.0
# HTTPS
parcel src/index.html --https
# Open browser
parcel src/index.html --open
```_
### Serveroptionen entwickeln
```bash
# Disable HMR
parcel src/index.html --no-hmr
# Disable source maps
parcel src/index.html --no-source-maps
# Custom dist directory
parcel src/index.html --dist-dir build
# Watch additional files
parcel src/index.html --watch-dir src/data
```_
### Proxy Konfiguration
```json
// package.json
{
"scripts": {
"start": "parcel src/index.html --port 3000"
},
"@parcel/resolver-default": {
"packageExports": true
}
}
```_
## Gebäude für die Produktion
### Grundlagen der Produktion
```bash
# Build for production
parcel build src/index.html
# Build with custom output directory
parcel build src/index.html --dist-dir build
# Build without source maps
parcel build src/index.html --no-source-maps
# Build without optimization
parcel build src/index.html --no-optimize
```_
### Konfiguration erstellen
```json
{
"scripts": {
"build": "parcel build src/index.html",
"build:analyze": "parcel build src/index.html --reporter @parcel/reporter-bundle-analyzer",
"build:stats": "parcel build src/index.html --reporter @parcel/reporter-bundle-buddy"
}
}
```_
### Produktionsoptimierungen
```bash
# Enable scope hoisting
parcel build src/index.html --experimental-scope-hoisting
# Custom public URL
parcel build src/index.html --public-url /my-app/
# Detailed bundle report
parcel build src/index.html --detailed-report
```_
## Vermögenswerte
### JavaScript und TypeScript
```javascript
// ES6 modules
import { helper } from './utils/helper.js';
// CommonJS
const lodash = require('lodash');
// Dynamic imports
const module = await import('./dynamic-module.js');
// TypeScript
import { Component } from './Component.ts';
```_
### CSS und Preprozessoren
```css
/* CSS imports */
@import './normalize.css';
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
/* CSS modules */
.container {
composes: flex from './layout.css';
background: var(--primary-color);
}
```_
```scss
// SCSS
@import './variables';
.component {
background: $primary-color;
&:hover {
background: darken($primary-color, 10%);
}
}
```_
```less
// Less
@import './variables.less';
.component {
background: @primary-color;
&:hover {
background: darken(@primary-color, 10%);
}
}
```_
### Bilder und Vermögenswerte
```javascript
// Import images
import logo from './assets/logo.png';
import icon from './assets/icon.svg';
// Use in HTML
document.getElementById('logo').src = logo;
// CSS background images
.hero {
background-image: url('./assets/hero.jpg');
}
```_
### Schriftarten
```css
/* Font imports */
@font-face {
font-family: 'CustomFont';
src: url('./assets/fonts/custom-font.woff2') format('woff2'),
url('./assets/fonts/custom-font.woff') format('woff');
}
body {
font-family: 'CustomFont', sans-serif;
}
```_
### JSON und Datendateien
```javascript
// Import JSON
import data from './data.json';
import config from './config.json';
// Import text files
import template from './template.html';
import shader from './shader.glsl';
```_
## Transformationen
### Babel Konfiguration
```json
// .babelrc
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["> 1%", "last 2 versions"]
}
}],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import"
]
}
```_
### PostCSS Konfiguration
```javascript
// .postcssrc
{
"plugins": {
"autoprefixer": {
"grid": true
},
"cssnano": {
"preset": "default"
}
}
}
```_
### TypScript Konfiguration
```json
// tsconfig.json
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"lib": ["dom", "dom.iterable", "es6"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
```_
### React Configuration
```javascript
// React component
import React from 'react';
import './Component.css';
export default function Component({ title }) {
return (
<div className="component">
<h1>{title}</h1>
</div>
);
}
```_
### Vue Konfiguration
```vue
<!-- Vue component -->
<template>
<div class="component">
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
props: ['title']
}
</script>
<style scoped>
.component {
padding: 20px;
}
</style>
```_
## Code Splitting
### Dynamische Importe
```javascript
// Dynamic import for code splitting
async function loadModule() {
const { default: Module } = await import('./heavy-module.js');
return new Module();
}
// React lazy loading
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
```_
### Bundle Splitting
```javascript
// Vendor bundle splitting
import React from 'react';
import ReactDOM from 'react-dom';
import lodash from 'lodash';
// App code
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
```_
### Routenbasierte Splitting
```javascript
// React Router with code splitting
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Suspense, lazy } from 'react';
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
const Contact = lazy(() => import('./pages/Contact'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Suspense>
</Router>
);
}
```_
## Hot Modul Ersatz
### HMR in JavaScript
```javascript
// Enable HMR for a module
if (module.hot) {
module.hot.accept('./component.js', function() {
// Re-render component
render();
});
}
// HMR with state preservation
if (module.hot) {
module.hot.accept();
if (module.hot.data) {
// Restore state
restoreState(module.hot.data.state);
}
module.hot.dispose((data) => {
// Save state
data.state = getCurrentState();
});
}
```_
### React HMR
```javascript
// React Fast Refresh (automatic with Parcel)
import React from 'react';
function App() {
const [count, setCount] = React.useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default App;
```_
### CSS HMR
```css
/* CSS changes are automatically hot reloaded */
.component {
background: blue; /* Change this and see instant update */
padding: 20px;
border-radius: 8px;
}
```_
## Umweltvariablen
### Verwendung von Umweltvariablen
```javascript
// Access environment variables
const apiUrl = process.env.API_URL || 'http://localhost:3000';
const isDevelopment = process.env.NODE_ENV === 'development';
console.log('API URL:', apiUrl);
console.log('Development mode:', isDevelopment);
```_
### .env Dateien
```bash
# .env
API_URL=https://api.example.com
FEATURE_FLAG=true
DEBUG=false
```_
```bash
# .env.development
API_URL=http://localhost:3000
DEBUG=true
```_
```bash
# .env.production
API_URL=https://api.production.com
DEBUG=false
```_
### Umweltspezifische Bauten
```json
{
"scripts": {
"start": "NODE_ENV=development parcel src/index.html",
"build": "NODE_ENV=production parcel build src/index.html",
"build:staging": "NODE_ENV=staging parcel build src/index.html"
}
}
```_
## Plugins
### Installation von Plugins
```bash
# Install common plugins
npm install --save-dev @parcel/transformer-sass
npm install --save-dev @parcel/transformer-less
npm install --save-dev @parcel/transformer-stylus
npm install --save-dev @parcel/transformer-typescript
```_
### Plugin Konfiguration
```json
// .parcelrc
{
"extends": "@parcel/config-default",
"transformers": {
"*.{ts,tsx}": ["@parcel/transformer-typescript-tsc"],
"*.scss": ["@parcel/transformer-sass"]
},
"reporters": ["@parcel/reporter-dev-server", "@parcel/reporter-bundle-analyzer"]
}
```_
### Individuelle Plugins
```javascript
// parcel-plugin-custom.js
const { Transformer } = require('@parcel/plugin');
module.exports = new Transformer({
async transform({ asset }) {
const code = await asset.getCode();
// Transform the code
const transformedCode = customTransform(code);
asset.setCode(transformedCode);
return [asset];
}
});
```_
### Beliebte Plugins
```bash
# Bundle analyzer
npm install --save-dev @parcel/reporter-bundle-analyzer
# Service worker
npm install --save-dev parcel-plugin-sw-precache
# Compression
npm install --save-dev parcel-plugin-compress
# Clean dist
npm install --save-dev parcel-plugin-clean-dist
```_
## Konfiguration
### Basic .parcelrc
```json
{
"extends": "@parcel/config-default",
"transformers": {
"*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx}": [
"@parcel/transformer-js",
"@parcel/transformer-react-refresh-wrap"
]
}
}
```_
### Erweiterte Konfiguration
```json
{
"extends": "@parcel/config-default",
"resolvers": ["@parcel/resolver-default"],
"transformers": {
"*.{ts,tsx}": ["@parcel/transformer-typescript-tsc"],
"*.{js,jsx}": ["@parcel/transformer-js"],
"*.{css,scss,sass}": ["@parcel/transformer-sass", "@parcel/transformer-css"],
"*.{html,htm}": ["@parcel/transformer-html"]
},
"bundler": "@parcel/bundler-default",
"namers": ["@parcel/namer-default"],
"runtimes": ["@parcel/runtime-js", "@parcel/runtime-browser-hmr"],
"optimizers": {
"*.{js,mjs,jsm,jsx,ts,tsx}": ["@parcel/optimizer-terser"],
"*.{css,scss,sass}": ["@parcel/optimizer-css"]
},
"packagers": {
"*.html": "@parcel/packager-html",
"*.{js,mjs,jsm,jsx,ts,tsx}": "@parcel/packager-js",
"*.{css,scss,sass}": "@parcel/packager-css"
},
"compressors": {
"*": ["@parcel/compressor-gzip"]
},
"reporters": ["@parcel/reporter-dev-server"]
}
```_
### Zielkonfiguration
```json
// package.json
{
"targets": {
"default": {
"distDir": "dist"
},
"modern": {
"engines": {
"browsers": "Chrome 80"
}
},
"legacy": {
"engines": {
"browsers": "> 1%"
}
}
}
}
```_
## Optimierung
### Produktionsoptimierungen
```bash
# Build with optimizations
parcel build src/index.html
# Disable optimizations
parcel build src/index.html --no-optimize
# Enable experimental optimizations
parcel build src/index.html --experimental-scope-hoisting
```_
### Bundle Größe Optimierung
```javascript
// Tree shaking (automatic with ES modules)
import { debounce } from 'lodash-es';
// Avoid importing entire libraries
import debounce from 'lodash/debounce';
// Use dynamic imports for large dependencies
async function loadChart() {
const { Chart } = await import('chart.js');
return Chart;
}
```_
### Bildoptimierung
```html
<!-- Automatic image optimization -->
<img src="./image.jpg" alt="Optimized image" />
<!-- WebP support -->
<picture>
<source srcset="./image.webp" type="image/webp">
<img src="./image.jpg" alt="Image with WebP fallback">
</picture>
```_
### CSS Optimierung
```css
/* Automatic CSS optimization */
.component {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* PostCSS plugins handle vendor prefixes */
.modern-feature {
backdrop-filter: blur(10px);
}
```_
## Ziele
### Browser-Ziele
```json
// package.json
{
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
```_
### Node.js Ziel
```json
{
"targets": {
"node": {
"context": "node",
"engines": {
"node": ">= 12"
}
}
}
}
```_
### Bibliothek Ziel
```json
{
"targets": {
"library": {
"source": "src/index.js",
"distDir": "lib"
}
}
}
```_
### Mehrere Ziele
```json
{
"targets": {
"modern": {
"engines": {
"browsers": "Chrome 80"
},
"distDir": "dist/modern"
},
"legacy": {
"engines": {
"browsers": "> 1%"
},
"distDir": "dist/legacy"
}
}
}
```_
## Caching
### Bauen Sie Caching
```bash
# Cache location
.parcel-cache/
# Clear cache
rm -rf .parcel-cache
# Disable cache
parcel build src/index.html --no-cache
```_
### HTTP Caching
```javascript
// Automatic content hashing for long-term caching
// Output: main.a1b2c3d4.js
// Service worker for caching
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
```_
### Cache Konfiguration
```json
{
"cacheDir": ".cache",
"cache": true
}
```_
## Quelle Maps
### Quelle Map Konfiguration
```bash
# Enable source maps (default in development)
parcel src/index.html
# Disable source maps
parcel src/index.html --no-source-maps
# Production source maps
parcel build src/index.html --source-maps
```_
### Quelle Kartentypen
```json
// .parcelrc
{
"extends": "@parcel/config-default",
"optimizers": {
"*.js": {
"sourceMap": {
"inline": false,
"inlineSources": true
}
}
}
}
```_
## Bundanalyse
### Das ist die richtige Lösung.
```bash
# Install bundle analyzer
npm install --save-dev @parcel/reporter-bundle-analyzer
# Build with analyzer
parcel build src/index.html --reporter @parcel/reporter-bundle-analyzer
Das ist alles.¶
```bash
Install bundle buddy¶
npm install --save-dev @parcel/reporter-bundle-buddy
Generate bundle buddy report¶
parcel build src/index.html --reporter @parcel/reporter-bundle-buddy ```_
Zollanalyse¶
```javascript // analyze-bundle.js const fs = require('fs'); const path = require('path');
function analyzeBundles() { const distDir = path.join(__dirname, 'dist'); const files = fs.readdirSync(distDir);
files.forEach(file => {
const filePath = path.join(distDir, file);
const stats = fs.statSync(filePath);
console.log(${file}: ${(stats.size / 1024).toFixed(2)} KB);
});
}
analyzeBundles(); ```_
Migration¶
Von Webpack¶
```javascript // webpack.config.js (remove this file) // Parcel handles most webpack functionality automatically
// Update package.json scripts { "scripts": { "start": "parcel src/index.html", "build": "parcel build src/index.html" } } ```_
Von React App erstellen¶
```bash
Remove react-scripts¶
npm uninstall react-scripts
Install Parcel¶
npm install --save-dev parcel
Update scripts¶
{ "scripts": { "start": "parcel public/index.html", "build": "parcel build public/index.html" } } ```_
Von Rollup¶
```javascript // Remove rollup.config.js // Update package.json
{ "source": "src/index.js", "main": "dist/index.js", "scripts": { "build": "parcel build" } } ```_
Migration Checkliste¶
- Entfernen Sie alte Paketer Konfigurationsdateien
- Update Paket.json scripts
- Installieren Sie Paket und entfernen Sie alte Bündelr
- Importpfade nach Bedarf aktualisieren
- Konfigurieren .parcelrc, wenn benutzerdefinierte Transformationen benötigt werden
- Testentwicklung und Produktionsaufbau
- Aktualisierung von CI/CD-Pipelines
Best Practices¶
Projektorganisation¶
```bash
Recommended structure¶
src/ ├── index.html # Entry point ├── index.js # Main JavaScript ├── styles/ # Global styles ├── components/ # Reusable components ├── pages/ # Page components ├── utils/ # Utility functions ├── assets/ # Static assets └── types/ # TypeScript types ```_
Performance Best Practices¶
- ** Dynamische Importe** zur Codespaltung
- Optimieren Sie Bilder mit entsprechenden Formaten
- Minimize Bündelgröße mit Baumschütteln
- Einstellbare Kompression für Produktionsanlagen
- **Verwendung von Inhalten ** für Caching
Entwicklung Best Practices¶
- ** Verwenden Sie HMR** für schnellere Entwicklung
- ** Quellkarten aktivieren* für Debugging
- **Konfigurieren Sie Linting* mit ESLint und Prettier
- ** Verwenden Sie TypeScript** für bessere Entwicklungserfahrung
- Einrichten von Tests mit Jest oder anderen Frameworks
Produktion Best Practices¶
- Optimieren Sie für Zielbrowser mit Browserliste
- ** Alle Optimierungen** in Produktionsgebäuden aktivieren
- ** Verwenden Sie Umgebungsvariablen* für Konfiguration
- Monitor Bündelgröße mit Analysewerkzeugen
- ** Test baut** vor dem Einsatz
--
Zusammenfassung¶
Parcel ist ein Zero-Configuration Build-Tool, das eine ausgezeichnete Entwicklererfahrung mit minimalem Setup bietet. Zu den wichtigsten Merkmalen gehören:
- **Zero Konfiguration*: Arbeiten aus der Box für die meisten Projekte
- **Fast Builds*: Verwendet Multicore-Verarbeitung und Caching
- **Hot Modul Ersatz*: Instant Updates während der Entwicklung
- **Asset Handling*: Unterstützt alle gängigen Dateitypen
- ** Code Splitting**: Automatische und manuelle Codespaltung
- Tree Shaking: Entfernt ungenutzten Code automatisch
- **Quelle Maps*: Eingebaute Quellkartenunterstützung
- ** Optimierung**: Automatische Produktionsoptimierungen
Durch den Einsatz von Parcels Einfachheit und Leistung können Sie sich auf den Aufbau Ihrer Anwendung konzentrieren, anstatt Bauwerkzeuge zu konfigurieren, während Sie noch die Flexibilität haben, bei Bedarf anzupassen.
<= <= <= <================================================================================= Funktion copyToClipboard() {\cHFFFF} const commands = document.querySelectorAll('code'); alle Befehle = ''; Befehle. Für jede(cmd) => alle Befehle += cmd.textContent + '\n'); navigator.clipboard.writeText (allCommands); Alarm ('Alle Befehle, die in die Zwischenablage kopiert werden!'); }
Funktion generierenPDF() { Fenster.print(); }