# Technical Documentation: wesbos/JavaScript30

> ℹ️ **Provenance:** Hybrid Fusion: `wesbos/JavaScript30` + `wesbos/website` · [CodeWiki Reference](https://codewiki.google/github.com/wesbos/JavaScript30) · Recency: Active (< 180 days)

## 1. Project Overview & Quickstart (wesbos/JavaScript30)

# JavaScript30

Starter Files + Completed solutions for the JavaScript 30 Day Challenge.

Grab the course at [https://JavaScript30.com](https://JavaScript30.com)

## Community #JavaScript30 Content

Feel free to submit a PR by adding a link to your own recaps, guides, or reviews!

* [Arjun Khode’s blog](http://thesagittariusme.blogspot.com/search/label/JS30) about summaries for each day, including fixed glitches, bugs and extra features.
* [Nitish Dayal's Text Guides](https://github.com/nitishdayal/JavaScript30) are great for those who like reading over watching.
* [Thorsten Frommen](https://tfrommen.de/tag/javascript-30/) shares how he solved the exercises before viewing the answers.
* [Soyaine 写的中文指南](https://github.com/soyaine/JavaScript30)包含了过程记录和难点解释
* [Aaron的语雀学习小组](https://github.com/A-aronYang/JavaScript30)包含中文文档，案例和相关资料
* [乔木 录制的讲解视频](https://b23.tv/pSa7rdu) 看中文讲解视频一起学习 Javascript30 吧! Javascript30 中 CSS/JS/HTML 视频讲解
* [Ayo Isaiah's](https://freshman.tech/archive/#javascript30) Recaps and Lessons Learned.
* [Adriana Rios](https://stpcollabr8nlstn.github.io/JavaScript30/) shares her alternative solutions.
* [Michael Einsohn](http://30daysofjs.michaeleinsohn.com) publishes each challenge after watching the video once.
* [Mike Ekkel](https://medium.com/@mike_ekkel/javascript-30-a-30-day-vanilla-js-challenge-6a733fc9f62c#.9frjtaje9)
* [Yusef Habib](https://github.com/yhabib/JavaScript30) lessons and tricks learned, and a [gh-page](https://yhabib.github.io/JavaScript30/) to see working all the mini-projects.
* [Amelie Yeh](https://github.com/amelieyeh/JS30) 30 lesson notes with things I've learned, and those important recaps. and directly view my demos [here](https://amelieyeh.github.io/JS30/) 🇹🇼😄
* [Winar](https://github.com/winar-jin/JavaScript30-Challenge)的JavaScript30天挑战，记录练习过程，重难点和其他的解决方案。🎨
* [Rayhatron](https://rayhatron.github.io/blog/) - walkthroughs, recaps, and lessons learned.
* [Andrei Dobra](https://github.com/andreidbr/JS30) Full repo with lessons learned and a [gh-page](https://andreidbr.github.io/JS30/) with all the exercises.
* [从零到壹全栈部落](https://github.com/liyuechun/JavaScript30-liyuechun),春哥发起的从零到壹全栈部落，旨在带领大家一起学习，一起输出，文档化，代码化，中文视频化，全栈部落口号：输出是最好的学习方式。
* [Usmaan Ali's](https://github.com/usyyy/javascript/blob/master/JavaScript30/analysis.md) summary of the technical skills learned from each project. He's also posting them as separate blog posts [here](https://medium.com/@usyyy).
* [Axel](https://github.com/afuh/js30)'s lessons learned and a [showcase](https://afuh.github.io/js30/) with the projects.
* [Chris](https://github.com/dwatow/JavaScript30) 中文實戰，目標描述、過程紀錄。
* [Muhammad D. Ramadhan's](https://miayam.github.io) blog. He shamlesly mixed his personal life with 30 day JavaScript challenge to increase his learning retention. He also summarised the challenge on [one single page](https://miayam.github.io/js30). Do not read his blog!
* [Lee Keitel's Blog](https://blog.keitel.xyz/categories/javascript30/) includes summaries of each lesson, what I learned from each one, and my thoughts about the topic taught and using them in the future.
* [Dustin Hsiao](https://github.com/dustinhsiao21/Javascript30-dustin) 包含了各篇介紹、 效果Demo、各篇詳解及記錄過程，附上部分延伸閱讀及[gh-page](https://dustinhsiao21.github.io/Javascript30-dustin/)。
* [GuaHsu](https://github.com/guahsu/JavaScript30) - 紀錄各篇練習過程與心得，並嘗試擴充部分練習，也做了一個包含全部練習的[介紹站](http://guahsu.io/JavaScript30/)🇹🇼
* [Daniela](https://github.com/misslild)'s completed challenges on [GitHub Pages](https://misslild.github.io/WesBos-30day-Coding-challenge/) and [Codepen](https://codepen.io/collection/DapZeP/) :raised_hands: :muscle: :+1:
* [Dmitrii Pashutskii's](https://github.com/guar47) code of all challenges on [GitHub with Pages](https://github.com/guar47/javascript30Summary) and review [blog posts](https://blog.dpashutskii.com/tag/javascript30/).
* [Abid Hasan's](https://github.com/sabidhasan/javascript-30) completion of all challenges. This was awesome!! Learned so much! :+1:
* [Yusong Notes](https://sky172839465.github.io/course/js30) Records Yusong JS 30 days note and demo. :star2:
* [Ding's Implementation](https://github.com/Ding-Fan/javascript30) code and online demo.
* [Herminio Torres](https://github.com/herminiotorres/JavaScript30) lessons and tricks learned, and a [gh-page](https://herminiotorres.github.io/JavaScript30/) to see working all the mini-projects.
* [Dmytro Borysovskyi](https://github.com/dimabory) says many thanks for the course to Wes 🤝 It was incredible challenge 👌 The full repository with code available [here](https://github.com/dimabory/dimabory.github.io/tree/gh-pages/src/components/JavaScript30Days) and demos can be reached by the link to [gh-pages](https://dimabory.github.io/#/js30days).👍👍👍
* [Kizito](https://github.com/akhilome/)'s follow along [repo](https://github.com/akhilome/js30) with [completed challenges](https://akhilome.github.io/js30) and [notes](https://akhilome.github.io/js30/notes).
* [VannTile](https://github.com/vanntile)'s [repository](https://github.com/vanntile/JavaScript30) and [GitHub Pages showcase](https://vanntile.github.io/JavaScript30/). Thank you for a great ⌨️ experience.
* [Alex Kim](https://github.com/Alex-K1m/js30-challenge) completed all the challenges. You can check them out at [GitHub pages](https://alex-k1m.github.io/js30-challenge/).
* [Mikhail Thomas](https://github.com/seckela) created [JS30++](https://github.com/seckela/js30plusplus) to add another level of challenge on top of this already great course.
* [Ramon Morcillo](https://github.com/reymon359/JavaScript30) finished this awesome challenge!. You can see the showcase of his implementations on [this link](https://reymon359.github.io/JavaScript30/).
* [Santiago Escobar](https://github.com/sescobar99)'s [repository](https://github.com/sescobar99/javascript30-challenge) and [GitHub Pages showcase](https://sescobar99.github.io/javascript30-challenge/).
* [Harry Xie](https://github.com/a90100/JavaScript30) 紀錄 30 天的練習筆記在 [此連結](https://github.com/a90100/JavaScript30).
* [ Van Ribeiro's ](https://vanribeiro-30daysofjavascript.netlify.app/) about demos and recaps. On [GitHub Repo](https://github.com/vanribeiro/30days-Of-JavaScript) there's a summary about what was learned and researched.
* [Mugilan](https://github.com/Mugilan-Codes) is currently doing this challenge. Check out his [Repo](https://github.com/Mugilan-Codes/javascript-30) and the [Live Demo](https://mugilan-codes.github.io/javascript-30/).
* [Eshan Vohra](https://github.com/eshanvohra) is currently doing this challenge. Check out my repo [here](https://github.com/eshanvohra/JavaScript30).
* [RegusAl](https://github.com/RegusAl) is currently doing this challenge. Check out my repo [here](https://github.com/RegusAl/JavaScript30).
* [Ayush Gupta's](https://javascript30.ayushgupta.tech/) implementation of JavaScript30 challenge with some add-ons & updated design.
* [filipkowal](https://github.com/filipkowal/JS30-05-Flex-Panels-Deactivate) Fix to flex panels (5th  day) so the panels deactivate when clicked on another one.
* [Mo. Saif's](https://github.com/MoSaif00)note on lessons learned and a [gh-pages showcase](https://mosaif00.github.io/30-Days-JavaScript-Challenge/) for the projects.
* [Stiaannel's](https://stiaannel.co.za/my-projects/javascript30) implementation of the Javascript30 challenge, with small design changes and a couple of extra features.
* [Kelly CHI's](https://kellychi22.github.io/JavaScript30/) complete JavaScript30 challenges! Click the links to check demos and notes of each challenge. 🇹🇼 🌟
* [Issam Seghir](https://issam-seghir.github.io/JavaScript30/)  added custom solutions and styles 🍧, improved performance, including fixed bugs/issus 💢. , added articles for each exercise 📝.
* [Khush Gupta's](https://khushgupta14.github.io/JavaScript30/) implementation of the JavaScript30 challenge with custom UI and extended logic.

## Alternative Implementations
Here are some links of people who have done the tutorials, but in a different language or framework:

* [Thomas Mattacchione](https://github.com/tkjone/clojurescript-30) JavaScript 30 written in ClojureScript.
* [Dave Follett's](https://github.com/davefollett) blog series, [A New Vue on #JavaScript30](https://davefollett.io/categories/a-new-vue-on-javascript30/), where he explores re-implementing #JavaScript30 projects using [Vue](https://vuejs.org).
* [Akinjide Bankole](https://github.com/akinjide/JS30days) used Node.js with [Jade](http://jadelang.net) to solve the exercises.
* [Adrien Poly](https://github.com/adrienpoly/javascript30-stimulus) a modest attempt to convert Drum Kit, Video Player, Local Tapas, TypeHead to [Stimulus JS](https://stimulusjs.org/) framework in a Rails App.
* [Bogdan Lazar](https://github.com/tricinel/TypeScript30) all the JavaScript 30 written in [TypeScript](https://www.typescriptlang.org/).
* [Will Wager](https://github.com/wwags33/JavaScript30) another [TypeScript](https://www.typescriptlang.org/) implementation!
* [marcoSven](https://github.com/marcoSven) solution suggestion for [10 - Hold Shift and Check Checkboxes](https://github.com/marcoSven/JavaScript30/blob/master/10%20-%20Hold%20Shift%20and%20Check%20Checkboxes/index-FINISHED.html).
* [ALMaclaine](https://github.com/almaclaine) Javascript 30 written in [Dart 2.0](https://github.com/ALMaclaine/Dart30).
* [Connie Leung](https://github.com/railsstudent) Javascript 30 written in [Angular and RxJS](https://github.com/railsstudent/ng-rxjs-30).

## A note on Pull Requests

These are meant to be 1:1 copies of what is done in the video. If you found a better / different way to do things, great, but I will be keeping them the same as the videos.

The starter files + solutions will be updated if/when the videos are updated.

Thanks!

## 2. Official Technical Reference & Guides (wesbos/website)

## File: README.md

# 🌎 parcel-website

This is the source of the [parceljs.org](https://parceljs.org) website.

Aside from the homepage, each documentation page is generated from a markdown file using the [markdown-styles](https://github.com/mixu/markdown-styles) generator.

## Contributing

Start a local server using:

```bash
npm install
npm run build
npm start
```

The website is deployed using [Zeit Now](https://zeit.co/now).

### Changing the displayed language

Change the displayed language using a query string:

E.g.: access the Korean version using the following url: http://localhost:5000/?locale=ko

---

## File: now.json

{
  "alias": [
    "parceljs.org",
    "en.parceljs.org",
    "es.parceljs.org",
    "fr.parceljs.org",
    "it.parceljs.org",
    "ja.parceljs.org",
    "ko.parceljs.org",
    "pl.parceljs.org",
    "pt.parceljs.org",
    "ru.parceljs.org",
    "zh.parceljs.org",
    "uk.parceljs.org",
    "zh-tw.parceljs.org"
  ]
}

---

## File: package.json

{
  "name": "parcel-website",
  "version": "1.0.0",
  "description": "The parcel website",
  "main": "index.js",
  "repository": "git://git@github.com:parcel-bundler/website.git",
  "author": "Devon Govett <devongovett@gmail.com>",
  "license": "MIT",
  "scripts": {
    "build": "./build.sh",
    "clean": "rm -rf dist",
    "start": "node src/server.js",
    "format": "prettier --write 'src/**/*.{md,js,css,json}'",
    "deploy": "now"
  },
  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged"
    }
  },
  "dependencies": {
    "express": "^4.16.2"
  },
  "devDependencies": {
    "husky": "^1.1.2",
    "markdown-styles": "^3.1.10",
    "now": "^11.2.4",
    "prettier": "^1.14.3",
    "pretty-quick": "^1.8.0"
  }
}

---

## File: src/i18n/en/docs/api.md

# 📚 API

## Bundler

Instead of the CLI you can also use the API to initialise a bundler, for more advanced use-cases (e.g. custom processing after every build).
A watch example with every option explained:

```Javascript
const Bundler = require('parcel-bundler');
const Path = require('path');

// Single entrypoint file location:
const entryFiles = Path.join(__dirname, './index.html');
// OR: Multiple files with globbing (can also be .js)
// const entryFiles = './src/*.js';
// OR: Multiple files in an array
// const entryFiles = ['./src/index.html', './some/other/directory/scripts.js'];

// Bundler options
const options = {
  outDir: './dist', // The out directory to put the build files in, defaults to dist
  outFile: 'index.html', // The name of the outputFile
  publicUrl: './', // The url to serve on, defaults to dist
  watch: true, // Whether to watch the files and rebuild them on change, defaults to process.env.NODE_ENV !== 'production'
  cache: true, // Enabled or disables caching, defaults to true
  cacheDir: '.cache', // The directory cache gets put in, defaults to .cache
  contentHash: false, // Disable content hash from being included on the filename
  global: 'moduleName', // Expose modules as UMD under this name, disabled by default
  minify: false, // Minify files, enabled if process.env.NODE_ENV === 'production'
  scopeHoist: false, // Turn on experimental scope hoisting/tree shaking flag, for smaller production bundles
  target: 'browser', // Browser/node/electron, defaults to browser
  bundleNodeModules: false, // By default, package.json dependencies are not included when using 'node' or 'electron' with 'target' option above. Set to true to adds them to the bundle, false by default
  https: { // Define a custom {key, cert} pair, use true to generate one or false to use http
    cert: './ssl/c.crt', // Path to custom certificate
    key: './ssl/k.key' // Path to custom key
  },
  logLevel: 3, // 5 = save everything to a file, 4 = like 3, but with timestamps and additionally log http requests to dev server, 3 = log info, warnings & errors, 2 = log warnings & errors, 1 = log errors
  hmr: true, // Enable or disable HMR while watching
  hmrPort: 0, // The port the HMR socket runs on, defaults to a random free port (0 in node.js resolves to a random free port)
  sourceMaps: true, // Enable or disable sourcemaps, defaults to enabled (minified builds currently always create sourcemaps)
  hmrHostname: '', // A hostname for hot module reload, default to ''
  detailedReport: false // Prints a detailed report of the bundles, assets, filesizes and times, defaults to false, reports are only printed if watch is disabled
};

(async function() {
  // Initializes a bundler using the entrypoint location and options provided
  const bundler = new Bundler(entryFiles, options);

  // Run the bundler, this returns the main bundle
  // Use the events if you're using watch mode as this promise will only trigger once and not for every rebuild
  const bundle = await bundler.bundle();
})();
```

If you want to use/start the built-in development server of Parcel you can use `bundler.serve()`. This calls `bundler.bundle()` and starts a simple http (or https) server. `serve()` takes in 3 arguments (they are all optional), first one is port, second one is https (this can either be an object `{cert,key}` pointing to the location of key and cert file or `true` to generate a key) and the third one is the host.

### Events

This is a list of all bundler events

- `bundled` gets called once Parcel has successfully finished bundling, the main [bundle](#bundle) instance gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('bundled', (bundle) => {
  // bundler contains all assets and bundles, see documentation for details
});
// Call this to start bundling
bundler.bundle();
```

- `buildEnd` gets called after each build (aka **including every rebuild**), this also emits if an error occurred

```Javascript
const bundler = new Bundler(...);
bundler.on('buildEnd', () => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

- `buildStart` gets called at the start of the first build, the `entryFiles` Array gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('buildStart', entryPoints => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

- `buildError` gets called every time an error occurs during builds, the `Error` Object gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('buildError', error => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

### Bundle

A `Bundle` is what Parcel uses to bundle assets together, this also contains child and sibling bundles to be able to build a bundle tree.

#### Properties

- `type`: The type of assets it contains (e.g. js, css, map, ...)
- `name`: The name of the bundle (generated using `Asset.generateBundleName()` of `entryAsset`)
- `parentBundle`: The parent bundle, is null in case of the entry bundle
- `entryAsset`: The entryPoint of the bundle, used for generating the name and gathering assets.
- `assets`: A `Set` of all assets inside the bundle
- `childBundles`: A `Set` of all child bundles
- `siblingBundles`: A `Set` of all sibling bundles
- `siblingBundlesMap`: A `Map<String(Type: js, css, map, ...), Bundle>` of all sibling bundles
- `offsets`: A `Map<Asset, number(line number inside the bundle)>` of all the locations of the assets inside the bundle, used to generate accurate source maps

#### Tree

The `Bundle` contains a `parentBundle`, `childBundles` and `siblingBundles`, all these properties together create a fast to iterate bundle tree.

A very basic example of an asset tree and it's generated bundle Tree

##### Asset tree:

`index.html` requires `index.js` and `index.css`.

`index.js` requires `test.js` and `test.txt`

```Text
index.html
-- index.js
 |--- test.js
 |--- test.txt
-- index.css
```

##### Bundle Tree:

`index.html` gets used as an entry asset for the main bundle, this main bundle creates two child bundles one for `index.js` and one for `index.css` this because they both are different from the `html` type.

`index.js` requires two files, `test.js` and `test.txt`.

`test.js` gets added to the assets of the `index.js` bundle, as it is of the same type as `index.js`

`test.txt` creates a new bundle and gets added as a child of the `index.js` bundle as it is a different assetType than `index.js`

`index.css` has no requires and therefore only contains it's entry Asset.

`index.css` and `index.js` bundles are siblingBundles of each other as they share the same parent.

```Text
index.html
-- index.js (includes index.js and test.js)
 |--- test.txt (includes test.txt)
-- index.css (includes index.css)
```

### Middleware

Middleware can be used to hook into an http server (e.g. `express` or node `http`).

An example of using the Parcel middleware with express

```Javascript
const Bundler = require('parcel-bundler');
const app = require('express')();

const file = 'index.html'; // Pass an absolute path to the entrypoint here
const options = {}; // See options section of api docs, for the possibilities

// Initialize a new bundler using a file and options
const bundler = new Bundler(file, options);

// Let express use the bundler middleware, this will let Parcel handle every request over your express server
app.use(bundler.middleware());

// Listen on port 8080
app.listen(8080);
```

---

## File: src/i18n/en/docs/asset_types.md

# 📝 Asset Types

As described in the [Assets documentation](assets.html), Parcel represents each input file as an `Asset`. Asset types are represented as classes inheriting from the base `Asset` class and implementing the required interface to parse, analyze dependencies, transform, and code generate.

Because Parcel processes assets in parallel across multiple processor cores, the transforms that asset types can perform are limited to those that operate on a single file at a time. For transforms across multiple files, a custom [Packager](packagers.html) can be used.

## Asset Interface

```javascript
const { Asset } = require('parcel-bundler')

class MyAsset extends Asset {
  type = 'foo' // set the main output type.

  async parse(code) {
    // parse code to an AST
    return ast
  }

  async pretransform() {
    // optional. transform prior to collecting dependencies.
  }

  collectDependencies() {
    // analyze dependencies
    this.addDependency('my-dep')
  }

  async transform() {
    // optional. transform after collecting dependencies.
  }

  async generate() {
    // code generate. you can return multiple renditions if needed.
    // results are passed to the appropriate packagers to generate final bundles.
    return [
      {
        type: 'foo',
        value: 'my stuff here' // main output
      },
      {
        type: 'js',
        value: 'some javascript', // alternative rendition to be placed in JS bundle if needed
        sourceMap
      }
    ]
  }

  async postProcess(generated) {
    // Process after all code generating has been done
    // Can be used for combining multiple asset types
  }
}

module.exports = MyAsset
```

## Registering an Asset Type

You can register your asset type with a bundler using the `addAssetType` method. It accepts a file extension to register, and the path to your asset type module. It is a path rather than the actual object so that it can be passed to worker processes.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addAssetType('.ext', require.resolve('./MyAsset'))
```

---

## File: src/i18n/en/docs/assets.md

# 📦 Assets

Parcel is based around assets. An asset can represent any file, but Parcel has special support for certain types of assets like JavaScript, CSS, and HTML files. Parcel automatically analyzes the dependencies referenced in these files and includes them in the output bundle. Assets of similar types are grouped together into the same output bundle. If you import an asset of a different type (for example, if you imported a CSS file from JS), it starts a child bundle and leaves a reference to it in the parent. This will be illustrated in the following sections.

If you are unable to find a certain asset type in the docs it might be that the documentation is out of date. For the entire list of supported asset types see [parcel/src/Parser.js](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/Parser.js#L10).
For the actual list of Parsers see [parcel/src/assets/](https://github.com/parcel-bundler/parcel/tree/master/packages/core/parcel-bundler/src/assets).

For any asset type not supported by default you can check if a plugin already exists:

- [Yarn](https://yarnpkg.com/en/packages?q=parcel-plugin-&p=1)
- [npm](https://www.npmjs.com/search?q=parcel-plugin-)
- [awesome-parcel](https://github.com/parcel-bundler/awesome-parcel#plugins)

or [create your own](https://parceljs.org/plugins.html).

---

## File: src/i18n/en/docs/cli.md

# 🖥 CLI

## Commands

### Serve

Starts up a development server, which will automatically rebuild your app as you change files and supports [hot module replacement](hmr.html) for fast development.

```bash
parcel index.html
```

### Build

Builds the assets once, it also enabled minification and sets the `NODE_ENV=production` environment variable. See [Production](production.html) for more details.

```bash
parcel build index.html
```

_NOTE:_ For special use cases, it's also possible to perform a single build from the `development` environment, like this:

```
NODE_ENV=development parcel build <entrypoint> --no-minify
```

It creates the same bundles than `serve`, but it doesn't watch or serve assets.


### Watch

The `watch` command is similar to `serve`, with the main difference being it doesn't start up a server.

```bash
parcel watch index.html
```

### Help

Displays all possible cli options

```bash
parcel help
```

### Version

Displays Parcel version number

```bash
parcel --version
```

## Options

### Output directory

Default: "dist"

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-dir build/output
# or
parcel build entry.js -d build/output
```

```base
root
- build
- - output
- - - entry.js
```

### Set the public URL to serve on

Default: "/"

Available in: `serve`, `watch`, `build`

```bash
parcel entry.js --public-url ./dist/
```

will output:

```html
<link rel="stylesheet" type="text/css" href="dist/entry.1a2b3c.css">
<!-- or -->
<script src="dist/entry.e5f6g7.js"></script>
```

### Target

Default: browser

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --target node
```

⚠️ Target `node` and `electron` will not bundle package.json's `dependencies` (but will include `devDependencies`). This behavior can be overriden using [--bundle-node-modules](#force-node-modules-bundling) flag (see below).

Possible targets: `node`, `browser`, `electron`

### Force node modules bundling

Default: false

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --target node --bundle-node-modules
```

By default, package.json's `dependencies` are not included when using `--target node` or `--target electron`. This flag adds them to the bundle.

### Cache directory

Default: ".cache"

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --cache-dir build/cache
```

### Port

Default: 1234

Available in: `serve`

```bash
parcel serve entry.js --port 1111
```

### Change Log level

Default: 3

Available in: `serve`, `watch`, `build`

```bash
parcel entry.js --log-level 1
```

| Loglevel | Effect                                                                                          |
| -------- | ----------------------------------------------------------------------------------------------- |
| 0        | Logging disabled                                                                                |
| 1        | Only log errors                                                                                 |
| 2        | Log errors and warnings                                                                         |
| 3        | Log errors, warnings and info                                                                   |
| 4        | Verbose (keep everything in log with timestamps  and also log http requests to dev server) |
| 5        | Debug (save everything to a file with timestamps)                                               |

### HMR Hostname

Default: `location.hostname` of current window

Available in: `serve`, `watch`

```bash
parcel entry.js --hmr-hostname parceljs.org
```

### HMR Port

Default: A random available port

Available in: `serve`, `watch`

```bash
parcel entry.js --hmr-port 8080
```

### Output filename

Default: Original filename

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-file output.html
```

This changes the output filename of the entrypoint bundle

### Print a detailed report

Default: Minimal report

Available in: `build`

```bash
parcel build entry.js --detailed-report
```

### Enable https

Default: https disabled

Available in: `serve`, `watch` (listen on HTTPS for HMR connections)

```bash
parcel build entry.js --https
```

⚠️ This flag generates a self-signed certificate, you might have to configure your browser to allow self-signed certificates for localhost.

### Set a custom certificate

Default: https disabled

Available in: `serve`, `watch`

```bash
parcel entry.js --cert certificate.cert --key private.key
```

### Open in browser

Default: open disabled

Available in: `serve`

```bash
parcel entry.js --open
```

### Disable source-maps

Default: source-maps enabled

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-source-maps
```

### Disable autoinstall

Default: autoinstall enabled

Available in: `serve`, `watch`

```bash
parcel entry.js --no-autoinstall
```

### Disable HMR

Default: HMR enabled

Available in: `serve`, `watch`

```bash
parcel entry.js --no-hmr
```

### Disable minification

Default: minification enabled

Available in: `build`

```bash
parcel build entry.js --no-minify
```

### Disable the filesystem cache

Default: cache enabled

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-cache
```

### Expose modules as UMD

Default: disabled

Available in: `serve`, `watch`, `build`

```bash
parcel serve entry.js --global myvariable
```

### Enable experimental scope hoisting/tree shaking support

Default: disabled

Available in: `build`

```bash
parcel build entry.js --experimental-scope-hoisting
```

For more information, see the [Tree Shaking section](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) of Devon Govett's post on Parcel 1.9.

---

## File: src/i18n/en/docs/code_splitting.md

# ✂️ Code Splitting

Parcel supports zero configuration code splitting out of the box. This allows you to split your application code into separate bundles which can be loaded on demand, which means smaller initial bundle sizes and faster load times. As the user navigates around in your application and modules are required, Parcel automatically takes care of loading child bundles on demand.

Code splitting is controlled by use of the dynamic `import()` function [syntax proposal](https://github.com/tc39/proposal-dynamic-import), which works like the normal `import` statement or `require` function, but returns a Promise. This means that the module is loaded asynchronously.

## Using dynamic imports

The following example shows how you might use dynamic imports to load a sub-page of your application on demand.

```javascript
// pages/about.js
export function render() {
  // Render the page
}
```

```javascript
import('./pages/about').then(function(page) {
  // Render page
  page.render()
})
```

## Dynamic imports with async/await

Because `import()` returns a Promise, you can also use async/await syntax. You probably need to configure Babel to transpile the syntax though, until it is more widely supported by browsers.

```javascript
const page = await import('./pages/about')
// Render page
page.render()
```

Dynamic imports are also lazily loaded in Parcel, so you can still put all your `import()` calls at the top of your file and the child bundles won't be loaded until they are used. The following example shows how you might lazily load sub-pages of an application dynamically.

```javascript
// Setup a map of page names to dynamic imports.
// These are not loaded until they are used.
const pages = {
  about: import('./pages/about'),
  blog: import('./pages/blog')
}

async function renderPage(name) {
  // Lazily load the requested page.
  const page = await pages[name]
  return page.render()
}
```

**Note:** If you would like to use async/await in browsers that don't support it natively, remember to include `babel-polyfill` in your app or `babel-runtime` + `babel-plugin-transform-runtime` in libraries.

```bash
yarn add babel-polyfill
```

```javascript
import 'babel-polyfill'
import './app'
```

Read the docs on [babel-polyfill](http://babeljs.io/docs/usage/polyfill) and [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime).

## Bundle resolution

Parcel infers the location of bundles automatically. This is done in the [bundle-url](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/builtins/bundle-url.js) module, and uses the stack trace to determine the path where the initial bundle was loaded.

This means you don't need to configure where bundles should be loaded from, but also means you must serve the bundles from the same location.

Parcel currently resolves bundles at the following protocols: `http`, `https`, `file`, `ftp`, `chrome-extension` and `moz-extension`.

---

## File: src/i18n/en/docs/coffeeScript.md

# CoffeeScript

_Supported extensions: `coffee`_

[CoffeeScript](https://coffeescript.org) is a language that transpiles to JavaScript, which allows you to use a shorter syntax and other features like [the existential operator](https://coffeescript.org/#existential-operator), [shorter array-splicing syntax](https://coffeescript.org/#slices), [block regular expressions](https://coffeescript.org/#regexes) and more.

```coffeescript
# log.coffee
console.log 'Hello there!'
```

```javascript
// index.js
import './log'
```

---

## File: src/i18n/en/docs/css.md

# CSS

_Supported extensions: `css`, `pcss`, `postcss`_

CSS assets can be imported from a JavaScript or HTML file:

```js
import './index.css';
```
```html
<link rel="stylesheet" type="text/css" href="index.css">
```

CSS assets can contain dependencies referenced by `@import` syntax as well as references to images, fonts, etc. via the `url()` function. Other CSS files that are `@import`ed are inlined into the same CSS bundle, and `url()` references are rewritten to their output filenames. All filenames should be relative to the current CSS file.

```css
/* Import another CSS file */
@import './other.css';

.test {
  /* Reference an image file */
  background: url('./images/background.png');
}
```

In addition to plain CSS, other compile-to-CSS languages like LESS, SASS, and Stylus are also supported, and work the same way.

# PostCSS

[PostCSS](http://postcss.org) is a tool for transforming CSS with plugins, like [autoprefixer](https://github.com/postcss/autoprefixer), [Preset Env](https://github.com/csstools/postcss-preset-env), and [CSS Modules](https://github.com/css-modules/css-modules). You can configure PostCSS with Parcel by creating a configuration file using one of these names: `.postcssrc` (JSON), `.postcssrc.js`, or `postcss.config.js`.

Install plugins in your app:

```bash
yarn add postcss-modules autoprefixer
```

Then, create a `.postcssrc`:

```json
{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}
```

Plugins are specified in the `plugins` object as keys, and options are defined using object values. If there are no options for a plugin, just set it to `true` instead.

Target browsers for Autoprefixer, cssnext and other tools can be specified in `.browserslistrc` file:

```
> 1%
last 2 versions
```

CSS Modules are enabled slightly differently using the a top-level `modules` key. This is because Parcel needs to have special support for CSS Modules since they export an object to be included in the JavaScript bundle as well. Note that you still need to install `postcss-modules` in your project.

## Usage with existing CSS libraries

For CSS Modules to work properly with existing modules they need to specify this support in their own `.postcssrc`.

## Set cssnano minify config

Parcel adds [cssnano](http://cssnano.co) to postcss in order to minify css in production build, where custom configuration can be set by creating `cssnano.config.js` file:

```js
module.exports = {
  preset: [
    'default',
    {
      calc: false,
      discardComments: {
        removeAll: true
      }
    }
  ]
}
```

---

## File: src/i18n/en/docs/elm.md

# Elm

_Supported extensions: `elm`_

[Elm](https://elm-lang.org/) is a functional language with an advanced type
system that ensures correctnes of your code and prevents confusing runtime
errors. With its focus on simplicity and speed, Elm is a great choice when it
comes to building webapps of all kinds. Parcel supports Elm right out of the box
without the need for any additional configuration.

```html
<!-- index.html -->

<html>
  <body>
    <main></main>
    <script src="./index.js"></script>
  </body>
</html>
```

```javascript
// index.js

import { Elm } from './Main.elm'

Elm.Main.init({
  node: document.querySelector('main')
})
```

```elm
-- Main.elm

import Browser
import Html exposing (h1, text)

main =
  h1 [] [ text "Hello, Elm!" ]
```

To learn more about Elm and its ecosystem of tools, see the official
[guide](https://guide.elm-lang.org/).

---

## File: src/i18n/en/docs/env.md

# 🌳 Environment Variables

Parcel uses [dotenv](https://github.com/motdotla/dotenv) to support loading environment variables from `.env` files.

`.env` files are to be stored alongside the `package.json` that contains your `parcel-bundler` dependency.

Parcel loads `.env` files with these specific names for the following `NODE_ENV` values:

| valid `.env` filenames   | `NODE_ENV=\*` | `NODE_ENV=test` |
| ------------------------ | ------------- | --------------- |
| `.env`                   | ✔️            | ✔️              |
| `.env.local`             | ✔️            | ✖️              |
| `.env.${NODE_ENV}`       | ✔️            | ✔️              |
| `.env.${NODE_ENV}.local` | ✔️            | ✔️              |

Notably:

- `NODE_ENV` defaults to `development`.
- `.env.local` is not loaded when `NODE_ENV=test` since [tests should produce the same results for everyone](https://github.com/parcel-bundler/parcel/blob/28df546a2249b6aac1e529dd629f506ba6b0a4bb/src/utils/env.js#L9)

---

## File: src/i18n/en/docs/getting_started.md

# 🚀 Getting Started

Parcel is a web application bundler, differentiated by its developer experience. It offers blazing fast performance utilizing multicore processing, and requires zero configuration.

First install Parcel using Yarn or npm:

Yarn:

```bash
yarn global add parcel-bundler
```

npm:

```bash
npm install -g parcel-bundler
```

Create a package.json file in your project directory using:

```bash
yarn init -y
```

or

```bash
npm init -y
```

Parcel can take any type of file as an entry point, but an HTML or JavaScript file is a good place to start. If you link your main JavaScript file in the HTML using a relative path, Parcel will also process it for you, and replace the reference with a URL to the output file.

Next, create an index.html and index.js file.

```html
<html>
<body>
  <script src="./index.js"></script>
</body>
</html>
```

```javascript
console.log('hello world')
```

Parcel has a development server built in, which will automatically rebuild your app as you change files and supports [hot module replacement](hmr.html) for fast development. Point it at your entry file:

```bash
parcel index.html
```

Now open http://localhost:1234/ in your browser. If hot module replacement isn't working you may need to [configure your editor](hmr.html#safe-write). You can also override the default port with the `-p ` option.

Use the development server when you don't have your own server, or your app is entirely client rendered. If you do have your own server, you can run Parcel in `watch` mode instead. This still automatically rebuilds as files change and supports hot module replacement, but doesn't start a web server.

```bash
parcel watch index.html
```

### Multiple entry files

In case you have more than one entry file, let's say `index.html` and `about.html`, you have 2 ways to run the bundler:

Specifying the file names:

```bash
parcel index.html about.html
```

Use tokens and create a glob:

```bash
parcel *.html
```

_NOTE:_ In case you have a file structure like this:

```
- folder-1
-- index.html
- folder-2
-- index.html
```

Going to http://localhost:1234/folder-1/ won't work, instead you will need to explicitly point to the file http://localhost:1234/folder-1/index.html.

### Building for production

When you're ready to build for production, the `build` mode turns off watching and only builds once. See the [Production](production.html) section for more details.

### Adding parcel to your project

Sometimes it's not possible to install Parcel globally e.g. if you're building on someone else's build agent or you want to use a CI to build your project programmatically. In this case, you can install and run Parcel as a local package.

To install with Yarn:

```bash
yarn add parcel-bundler --dev
```

To install with NPM:

```bash
npm install parcel-bundler --save-dev
```

Then, add these tasks scripts to your project, by modifying your `package.json`:

```json
{
  "scripts": {
    "dev": "parcel <your entry file>",
    "build": "parcel build <your entry file>"
  }
}
```

Then, you will be able to run it:

```bash
# To run in development mode
yarn dev
#or
npm run dev

# To run in production mode
yarn build
#or
npm run build
```

---

## File: src/i18n/en/docs/graphQL.md

# GraphQL

_Supported extensions: `gql`, `graphql`_

---

## File: src/i18n/en/docs/hmr.md

# 🔥 Hot Module Replacement

Hot Module Replacement (HMR) improves the development experience by automatically updating modules in the browser at runtime without needing a whole page refresh. This means that application state can be retained as you change small things. Parcel's HMR implementation supports both JavaScript and CSS assets out of the box. HMR is automatically disabled when bundling in production mode.

As you save files, Parcel rebuilds what changed and sends an update to any running clients containing the new code. The new code then replaces the old version, and is re-evaluated along with all parents. You can hook into this process using the `module.hot` API, which can notify your code when a module is about to be disposed, or when a new version comes in. Projects like [react-hot-loader](https://github.com/gaearon/react-hot-loader) can help with this process, and work out of the box with Parcel.

There are two methods to know about: `module.hot.accept` and `module.hot.dispose`. You call `module.hot.accept` with a callback function which is executed when that module or any of its dependencies are updated. `module.hot.dispose` accepts a callback which is called when that module is about to be replaced.

```javascript
if (module.hot) {
  module.hot.dispose(function() {
    // module is about to be replaced
  })

  module.hot.accept(function() {
    // module or one of its dependencies was just updated
  })
}
```

## Automagically installed dependencies

Whenever Parcel comes across a dependency that fits the `node_module` pattern and can't find it, Parcel tries to install this dependency using `yarn` or `npm` depending on finding a `yarn.lock` file or not. This prevents the developer from having to exit parcel or having multiple terminal windows open.

This only occurs in _development_ (using [`serve`](cli.md#serve) or [`watch`](cli.md#watch)), however in production (using [`build`](cli.md#build)) autoinstall is disabled to prevent unwanted side-effects on deployment.

You can disable this feature using [`--no-autoinstall`](cli.md#disable-autoinstall).

## Safe Write

Some text editors and IDE's have a feature called `safe write` that basically prevents data loss, by taking a copy of the file and renaming it when saved.

When using Hot Module Reload (HMR) this feature blocks the automatic detection of file updates, to disable `safe write` use the options provided below:

- `Sublime Text 3` add `atomic_save: "false"` to your user preferences.
- `IntelliJ` use search in the preferences to find "safe write" and disable it.
- `Vim` add `:set backupcopy=yes` to your settings.
- `WebStorm` uncheck `Use "safe write"` in Preferences > Appearance & Behavior > System Settings.

---

## File: src/i18n/en/docs/how_it_works.md

# 🛠 How It Works

Parcel transforms a tree of **assets** to a tree of **bundles**. Many other bundlers are fundamentally based around JavaScript assets, with other formats tacked on - e.g. inlined as strings into JS files. Parcel is file-type agnostic - it will work with any type of assets the way you'd expect, with no configuration. There are three steps to Parcel's bundling process.

### 1. Constructing the Asset Tree

Parcel takes as input a single entry asset, which could be any type: a JS file, HTML, CSS, image, etc. There are various [asset types](asset_types.html) defined in Parcel which know how to handle specific file types. The assets are parsed, their dependencies are extracted, and they are transformed to their final compiled form. This creates a tree of assets.

### 2. Constructing the Bundle Tree

Once the asset tree has been constructed, the assets are placed into a bundle tree. A bundle is created for the entry asset, and child bundles are created for dynamic `import()`s, which cause code splitting to occur.

Sibling bundles are created when assets of a different type are imported, for example if you imported a CSS file from JavaScript, it would be placed into a sibling bundle to the corresponding JavaScript.

If an asset is required in more than one bundle, it is hoisted up to the nearest common ancestor in the bundle tree so it is not included more than once.

### 3. Packaging

After the bundle tree is constructed, each bundle is written to a file by a [packager](packagers.html) specific to the file type. The packagers know how to combine the code from each asset together into the final file that is loaded by a browser.

---

## File: src/i18n/en/docs/html.md

# HTML

_Supported extensions: `htm`, `html`_

HTML assets are often the entry file that you provide to Parcel, but can also be referenced by JavaScript files, e.g. to provide links to other pages. URLs to scripts, styles, media, and other HTML files are extracted and compiled as described above. The references are rewritten in the HTML so that they link to the correct output files. All filenames should be relative to the current HTML file.

```html
<html>
<body>
  <!-- reference an image file -->
  <img src="./images/header.png">

  <a href="./other.html">Link to another page</a>

  <!-- import a JavaScript bundle -->
  <script src="./index.js"></script>
</body>
</html>
```

## Importing uncompiled assets

Adding links to files that Parcel can compile (e.g. JavaScript, TypeScript, SCSS, etc.) in HTML is supported. Parcel will automatically process the file and update the link to point to the compiled asset.

```html
<html>
  <head>
    <!-- include a SCSS file -->
    <link rel="stylesheet" href="./my-styles/style.scss">
  </head>
</html>
```

# PostHTML

[PostHTML](https://github.com/posthtml/posthtml) is a tool for transforming HTML with plugins. You can configure PostHTML with Parcel by creating a configuration file using one of these names: `.posthtmlrc` (JSON), `.posthtmlrc.js`, or `posthtml.config.js`.

Install plugins in your app:

```bash
yarn add posthtml-img-autosize
```

Then, create a `.posthtmlrc`:

```json
{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}
```

Plugins are specified in the `plugins` object as keys, and options are defined using object values. If there are no options for a plugin, just set it to `true` instead.

---

## File: src/i18n/en/docs/javascript.md

# JavaScript

_Supported extensions: `js`, `jsx`, `es6`, `jsm`, `mjs`_

The most traditional file type for web bundlers is JavaScript. Parcel supports both CommonJS and ES6 module syntax for importing files. It also supports dynamic `import()` function syntax to load modules asynchronously, which is discussed in the [Code Splitting](code_splitting.html) section. Dynamic imports can also import modules from URLs.

```javascript
// Import a module using CommonJS syntax
const dep = require('./path/to/dep')

// Import a module using ES6 import syntax
import dep from './path/to/dep'

// Import a module from a URL (e.g. CDN), using dynamic imports
import('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js').then(() => {
  console.log(_.VERSION);
});
```

You can also import non-JavaScript assets from a JavaScript file, e.g. CSS, HTML or even an image file. When you import one of these files, it is not inlined as in some other bundlers. Instead, it is placed in a separate bundle (e.g. a CSS file) along with all of its dependencies. When using [CSS Modules](https://github.com/css-modules/css-modules), the exported classes are placed in the JavaScript bundle. Other asset types export a URL to the output file in the JavaScript bundle so you can reference them in your code.

```javascript
// Import a CSS file
import './test.css'

// Import a CSS file with CSS modules
import classNames from './test.css'

// Import the URL to an image file
import imageURL from './test.png'

// Import an HTML file
import('./some.html')
// or:
import html from './some.html'
// or:
require('./some.html')
```

If you want to inline a file into the JavaScript bundle instead of reference it by URL, you can use the Node.js `fs.readFileSync` API to do that. The URL must be statically analyzable, meaning it cannot have any variables in it (other than `__dirname` and `__filename`).

```javascript
import fs from 'fs'

// Read contents as a string
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Read contents as a Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')

// Convert Buffer contents to an image
;<img src={`data:image/png;base64,${buffer.toString('base64')}`} />
```

### Images in JSX

Below is an example of how you could import an image file for use in JSX.

```js
// Import the image file
import megaMan from "./images/mega-man.png";

// JSX
<img src={megaMan} title="Mega Man" alt="Mega Man" />

// JSX (w/ custom path)
<img src={`/dist${megaMan}`} title="Mega Man" alt="Mega Man" />
```

# Babel

[Babel](https://babeljs.io) is a popular transpiler for JavaScript, with a large plugin ecosystem. Using Babel with Parcel works the same way as using it standalone or with other bundlers.

Install presets and plugins in your app:

```shell
yarn add --dev @babel/preset-react
```

Then, create a `.babelrc`:

```json
{
  "presets": ["@babel/preset-react"]
}
```
You can also put `babel` config in `package.json`
```json
"babel": {
  "presets": ["@babel/preset-react"]
}
```
NOTE: `package.json` takes precedence over `.babelrc`.

## Default Babel transforms

Parcel transpiles your code with `@babel/preset-env` by default, this is to transpile every module both internal (local requires) and external (node_modules) to match the defined target.

For the `browser` target it utilises [browserslist](https://github.com/browserslist/browserslist), the target browserlist can be defined in `package.json` (`engines.browsers` or `browserslist`) or using a configuration file (`browserslist` or `.browserslistrc`).

The browserlist target defaults to: `> 0.25%` (Meaning, support every browser that has 0.25% or more of the total amount of active web users)

For the `node` target, Parcel uses the `engines.node` defined in `package.json`, this default to _node 8_.

# Flow

[Flow](https://flow.org/) is a popular static type checker for JavaScript. Using Flow with Parcel is as simple as placing `// @flow` as the first line of your `js` files.

Parcel will automatically install the required Babel config to strip the Flow types from the compiled output, so there's nothing you have to worry about except [editor integrations](https://flow.org/en/docs/editors/) or supporting [Absolute Path module resolution](module_resolution.html#flow-with-absolute-or-tilde-resolution) with `.flowconfig`.

---

## File: src/i18n/en/docs/json.md

# JSON

_Supported extensions: `json`, `json5`_

---

## File: src/i18n/en/docs/less.md

# LESS

_Supported extensions: `less`_

It's not even necessary to install less 😱, parcel will automatically install less if it detects a less file.

You can import LESS files from JavaScript or html files.

```javascript
import './custom.less'
```

or

```html
<link href="./custom.less" rel="stylesheet">
```

---

## File: src/i18n/en/docs/meta.json

{
  "*": {
    "language": "en"
  }
}

---

## File: src/i18n/en/docs/module_resolution.md

# 📔 Module Resolution

The Parcel resolver implements a modified version of [the node_modules resolution](https://nodejs.org/api/modules.html#modules_all_together) algorithm.

## Module resolution
In addition to the standard algorithm, all [asset types supported by Parcel](https://parceljs.org/assets.html) are also resolved.

Module resolution can be relative to the:
- **entry root**: the directory of the entrypoint specified to Parcel, or the shared root (common parent directory) when multiple entrypoints are specified.
- **package root**: the directory of the nearest module root in `node_modules`.

### Absolute Paths

`/foo` resolves `foo` relative to the **entry root**.

### ~ Tilde Paths

`~/foo` resolves `foo` relative to the nearest **package root** or, if not found, the **entry root**.

### Glob file paths

Globs are wildcard imports that bundle multiple assets at once. Globs can match some or all files (`/assets/*.png`), as well as files in multiple directories (`/assets/**/*`);

This example bundles a directory of png files and returns the dist URLs.

```
import foo from "/assets/*.png";
// { 
//   'file-1': '/file-1.8e73c985.png',
//   'file-2': '/file-1.8e73c985.png'
// }
```

### package.json `browser` field
If a package includes a [package.browser field](https://docs.npmjs.com/files/package.json#browser), Parcel will use this instead of the package.main entry.

### Aliases

Aliases are supported through the `alias` field in `package.json`.

This example aliases `react` to `preact` and some local custom module that is not in `node_modules`.

```json
// package.json
{
  "name": "some-package",
  "devDependencies": {
    "parcel-bundler": "^1.7.0"
  },
  "alias": {
    "react": "preact-compat",
    "react-dom": "preact-compat",
    "local-module": "./custom/modules"
  }
}
```

Avoid using any special characters in your aliases as some may be used by Parcel and others by 3rd party tools or extensions. For example:

- `~` used by Parcel to resolve [tilde paths](#~-tilde-paths).
- `@` used by npm to resolve npm organisations.

We advise being explicit when defining your aliases, so please **specify file extensions**, otherwise Parcel will need to guess. See [JavaScript Named Exports](#javascript-named-exports) for an example of this.

## Common issues

### JavaScript Named Exports

Alias mappings apply to many asset types and do not specifically support mapping of JavaScript named exports. If you wish to map JS named exports you can do this:

```json
// package.json
{
  "name": "some-package",
  "alias": {
    "ipcRenderer": "./electron-ipc.js" // specify file extension
  }
}
```

and re-export the named export within the aliased file:

```js
// electron-ipc.js
module.exports = require('electron').ipcRenderer
```

### Flow with Absolute or Tilde Resolution

When using absolute path or tilde path module resolution you must configure Flow using the [module.name_mapper](https://flow.org/en/docs/config/options/#toc-module-name-mapper-regex-string) feature.

Given a project with this structure:

```
package.json
.flowconfig
src/
  index.html
  index.js
  components/
    apple.js
    banana.js
```

And `src/index.html` as an entrypoint, our **entry root** is the `src/` folder.

Therefore, to map this import correctly:

```javascript
// index.js
import Apple from '/components/apple'
```

We need Flow to replace the leading `/` in `'/components/apple'` with `src/`, resulting in `'src/components/apple'`.

The following setting in our `.flowconfig` achieves this replacement:

```
[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/src/\1'
```

Where `` is a Flow specific identifier indicating the location of our `.flowconfig`

NB: `module.name_mapper` can have multiple entries. This allows support for [Absolute](module_resolution.html#absolute-paths) or [Tilde](module_resolution.html#~-tilde-paths) Path Resolution in addition to [local module aliasing](module_resolution.html#aliasing) support.

### TypeScript ~ Resolution

TypeScript will need to know about your use of the `~` module resolution or alias mappings. Please refer to the [TypeScript Module Resolution docs](https://www.typescriptlang.org/docs/handbook/module-resolution.html) for further information.

```json
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~*": ["./src/*"]
    }
  }
}
```

### Monorepo Resolution

These are the advised usages with monorepos at this time:

Advised usage:

- use relative paths.
- use `/` for a root path if a root is required.

Unadvised usage:

- **avoid** `~` use within monorepos.

If you're a monorepo user and would like to contribute to these recommendations, please provide example repos when opening issues to support the discussion.

---

## File: src/i18n/en/docs/openGL.md

# OpenGL Shading Language (GLSL)

_Supported extensions: `glsl`, `vert`, `frag`_

---

## File: src/i18n/en/docs/packagers.md

# 📦 Packagers

In Parcel, a `Packager` combines multiple `Asset`s together into a final output bundle. This happens in the main process after all assets have been processed, and a bundle tree has been created. Packagers are registered based on output file type, and assets that have generated that output type are sent to that packager for production of the final output file.

## Packager Interface

```javascript
const { Packager } = require('parcel-bundler')

class MyPackager extends Packager {
  async start() {
    // optional. write file header if needed.
    await this.dest.write(header)
  }

  async addAsset(asset) {
    // required. write the asset to the output file.
    await this.dest.write(asset.generated.foo)
  }

  async end() {
    // optional. write file trailer if needed.
    await this.dest.end(trailer)
  }
}

module.exports = MyPackager
```

## Registering a Packager

You can register your packager with a bundler using the `addPackager` method. It accepts a file type to register, and the path to your packager module.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addPackager('foo', require.resolve('./MyPackager'))
```

---

## File: src/i18n/en/docs/plugins.md

# 🔌 Plugins

Parcel takes a slightly different approach from many other tools in that many common formats are included out of the box without the need to install and configure additional plugins. However, there are cases where you might want to extend Parcel in a nonstandard way, and for those times, plugins are supported. Installed plugins are automatically detected and loaded based on `package.json` dependencies.

When adding support for a new file format to Parcel, you should first consider how widespread it is, and how standardized the implementation is. If it is sufficiently widespread and standard, the format should probably be added to Parcel core rather than as a plugin that users need to install. If you have any doubts, [GitHub](https://github.com/parcel-bundler/parcel/issues) is the right place to discuss.

## Plugin API

Parcel plugins are very simple. They are simply modules that export a single function, which is called by Parcel automatically during initialization. The function receives as input the `Bundler` object, and can do configuration such as registering asset types and packagers.

```javascript
module.exports = function(bundler) {
  bundler.addAssetType('ext', require.resolve('./MyAsset'))
  bundler.addPackager('foo', require.resolve('./MyPackager'))
}
```

Publish this package on npm using `parcel-plugin-` or `@your-scope/parcel-plugin-` prefixes, and it will be automatically detected and loaded as described below.

## Using Plugins

Using plugins in Parcel could not be any simpler. All you need to do is install and save them in your `package.json`. Plugins should be named with the prefix `parcel-plugin-` or `@your-scope/parcel-plugin-`, e.g. `parcel-plugin-foo` or `@your-scope/parcel-plugin-foo`. Any dependencies listed in `package.json` with these prefixes will automatically be loaded during initialization.

---

## File: src/i18n/en/docs/production.md

# ✨ Production

When it comes time to bundle your application for production, you can use Parcel's production mode.

```bash
parcel build entry.js
```

## Optimisations

This disables watch mode and hot module replacement so it will only build once. It also enables the minifier for all output bundles to reduce file size. The minifiers used by Parcel are [terser](https://github.com/fabiosantoscode/terser) for JavaScript, [cssnano](http://cssnano.co) for CSS, and [htmlnano](https://github.com/posthtml/htmlnano) for HTML.

Enabling production mode also sets the `NODE_ENV=production` environment variable. Large libraries like React have development-only debugging features which are disabled by setting this environment variable, which results in smaller and faster builds for production.

To take advantage of the same kind of development-only debugging features, ensure that [terser's `dead_code` option](https://github.com/terser-js/terser#compress-options) is on (it is by default) and wrap any development-only debugging in a conditional check like so:

```js
if (process.env.NODE_ENV === 'development') { // Or, `process.env.NODE_ENV !== 'production'`
  // Only runs in development and will be stripped from production build.
}
```

## File naming strategy

To allow setting very aggresive caching rules to your cdn, for optimal performance and efficiency, Parcel hashes the file names of most bundles (according to whether the bundle should have a readable/rememberable name or not, mainly for SEO).

Parcel follows the following table, when it comes to naming bundles. (Entrypoints are never hashed)

|                   Bundle Type | Type               | Content hashed |
| ----------------------------: | ------------------ | :------------: |
|                           Any | Entrypoint         |       ❌       |
|                    JavaScript | `<script>`         |       ✅       |
|                    JavaScript | Dynamic import     |       ❌       |
|                    JavaScript | Service worker     |       ❌       |
|                          HTML | iframe             |       ❌       |
|                          HTML | anchor link        |       ❌       |
| Raw (Images, text files, ...) | Import/Require/... |       ✅       |

The file hash follows the following naming pattern: `<directory name>-<hash>.<extension>`

## Cross platform gotchas

In an effort to optimize production build performance, Parcel will try to determine the number of CPUs available at the machine running the build command so it can distribute the work accordingly. To do so, Parcel relies on the [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count) library.

Be aware that this module assumes you have the [`lscpu`](http://manpages.courier-mta.org/htmlman1/lscpu.1.html) program available in your system.

## Using a CI

If you want to integrate Parcel in your Continuous Integration system (e.g. Travis or Circle CI), you might need to install Parcel as a local dependency.

The instructions can be [found here](getting_started.html#adding-parcel-to-your-project).

---

## File: src/i18n/en/docs/pug.md

# Pug

_Supported extensions: `jade`, `pug`_

---

## File: src/i18n/en/docs/reasonML.md

# ReasonML

_Supported extensions: `ml`, `re`_

## ReasonML/BuckleScript

[ReasonML](https://reasonml.github.io/) compiles OCaml to JavaScript with the help of [BuckleScript](https://bucklescript.github.io). You can use ReasonML by installing dependencies and creating `bsconfig.json`:

```bash
$ yarn add bs-platform --dev
```

```json
// bsconfig.json
// from https://github.com/BuckleScript/bucklescript/blob/master/jscomp/bsb/templates/basic-reason/bsconfig.json

{
  "name": "whatever",
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```html
<!-- index.html -->
<!doctype html>
<html>
<body>
  <script src="./src/index.re"></script>
</body>
</html>
```

```reason
/* src/index.re */
print_endline("Hello World");
```

### ReasonReact

[ReasonReact](https://reasonml.github.io/reason-react/) is React binding for ReasonML. You can use it with Parcel too:

```bash
$ yarn add react react-dom reason-react
```

```diff
// bsconfig.json

{
  "name": "whatever",
+ "reason": {
+   "react-jsx": 2
+ },
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [
+   "reason-react"
  ],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```diff
<!-- index.html -->
<html>
<body>
+  <div id="app"></div>
  <script src="./src/index.re"></script>
</body>
</html>
```

```reason
/* src/Greeting.re */

let component = ReasonReact.statelessComponent("Greeting");

let make = (~name, _children) => {
  ...component,
  render: _self => <div> (ReasonReact.string("Hello! " ++ name)) </div>,
};
```

```reason
/* src/index.re */

ReactDOMRe.renderToElementWithId(<Greeting name="Parcel" />, "app");
```

---

## File: src/i18n/en/docs/recipes.md

# 🍰 Recipes

## React

First we need to install the dependencies for React.

[Blog Post](http://blog.jakoblind.no/react-parcel/)

```bash
npm install --save react
npm install --save react-dom
npm install --save-dev parcel-bundler
```

<sub>Or if you have the optional Yarn package manager installed</sub>

```bash
yarn add react
yarn add react-dom
yarn add --dev parcel-bundler
```

Add Start script to `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Preact

First we need to install the dependencies for Preact.

```bash
npm install --save preact
npm install --save preact-compat
npm install --save-dev parcel-bundler
npm install --save-dev babel-preset-preact
```

<sub>Or if you have the optional Yarn package manager installed</sub>

```bash
yarn add preact
yarn add preact-compat
yarn add --dev parcel-bundler
yarn add --dev babel-preset-preact
```

Then make sure the following Babel config is present.

```javascript
// .babelrc
{
  "presets": [
    "preact"
  ]
}
```

Add Start script to `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Vue

First we need to install the dependencies for Vue.

```bash
npm install --save vue
npm install --save-dev parcel-bundler
```

<sub>Or if you have the optional Yarn package manager installed</sub>

```bash
yarn add vue
yarn add --dev parcel-bundler
```

Add Start script to `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Typescript

First we need to add Parcel and Typescript to our project.

```bash
npm install --save-dev typescript
npm install --save-dev parcel-bundler
```

<sub>Or if you have the optional Yarn package manager installed</sub>

```bash
yarn add typescript --dev
yarn add --dev parcel-bundler
```

### Compiling from index.html

Add Start script to `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

Then, in your `index.html` file, simply reference your `.ts` file.

```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <!-- Here 👇 -->
    <script src="./myTypescriptFile.ts"></script>
</body>
</html>
```

Done!

### Compiling the `.ts` file directly

Add Start script to `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel myTypescriptFile.ts"
}
```

Done! 😄 Compiled `.js` file can be found inside the dist folder.

---

## File: src/i18n/en/docs/rust.md

# Rust

_Supported extensions: `rs`_

[Rust](https://www.rust-lang.org) is a systems programming language developed by Mozilla, which offers native performance with some interesting memory and thread safety characteristics. Rust recently added support for compiling to WebAssembly, and now Parcel makes it **super easy** to get started with zero configuration!

You can now simply import `.rs` files just like any other file type in Parcel! Assuming you have [Rustup](https://rustup.rs) installed, Parcel **automatically takes care installing** the right toolchains, targets, and other build pre-requisites. It works with [Cargo](https://github.com/rust-lang/cargo) projects, as well as straight-up Rust source files, automatically tracks your dependencies so **files are watched** and rebuilds happen when you save, and more!

Just like with `.wasm` files, `.rs` files can be imported with either synchronous or asynchonous imports.

```js
// synchronous import
import { add } from './add.rs'
console.log(add(2, 3))
// asynchronous import
const { add } = await import('./add.rs')
console.log(add(2, 3))
```

On the Rust side, you just need to make sure that function names aren’t mangled and are public.

```rs
#[no_mangle]
pub fn add(a: i32, b: i32) -> i32 {
  return a + b
}
```

---

## File: src/i18n/en/docs/scss.md

# SCSS

_Supported extensions: `sass`, `scss`_

SCSS compilation needs `sass` (JS version of `dart-sass`) module. To install it with npm:

```bash
npm install -D sass
```

Once you have `sass` installed you can import SCSS files from JavaScript files.

```javascript
import './custom.scss'
```

Dependencies in the SCSS files can be used with the `@import` statements.

If you don't have `sass` module installed before running Parcel, Parcel will install it automatically for you.

**Notes:** You can also use `node-sass` module for SCSS compilation. Using `node-sass` module will give you faster compilation. However, [an issue](https://github.com/parcel-bundler/parcel/issues/1836) has been reported using `node-sass` module with Parcel.

---

## File: src/i18n/en/docs/stylus.md

# Stylus

_Supported extensions: `styl`_

It's not even necessary to install Stylus 😱, parcel will automatically install Stylus if it detects a Stylus file.

You can import Stylus files from JavaScript or html files.

```javascript
import './custom.styl'
```

or

```html
<link href="./custom.styl" rel="stylesheet">
```

---

## File: src/i18n/en/docs/toml.md

# TOML

_Supported extensions: `toml`_

---

## File: src/i18n/en/docs/transforms.md

# 🐠 Transforms

While many bundlers require you to install and configure plugins to transform assets, Parcel has support for many common transforms and transpilers built in out of the box. You can transform JavaScript using [Babel](https://babeljs.io), CSS using [PostCSS](http://postcss.org), and HTML using [PostHTML](https://github.com/posthtml/posthtml). Parcel automatically runs these transforms when it finds a configuration file (e.g. `.babelrc`, `.postcssrc`) in a module. (In addition to any transforms specified in `.babelrc`, Parcel always uses Babel on all modules to compile modern JavaScript into a form supported by browsers. See the [JavaScript/Default Babel Transforms](javascript.html#default-babel-transforms) section for more information.)

## Third-Party Modules

Configuration files (such as `.babelrc`) will not be applied to files inside third-party `node_modules` by default. However, if the module's directory is symlinked (as is common in some monorepo conventions) and the module's `package.json` has the `source` field set, then configuration files inside the module's directory will be respected. Here are the types of values supported by the `source` field:

* Treat all files as source code, don't change the resolution

```json
{
  "main": "foo.js",
  "source": true
}
```

* When compiling from source, use bar.js as the entry point

```json
{
  "main": "foo.js",
  "source": "bar.js"
}
```

* When compiling from source, alias specific files

```json
{
  "main": "foo.js",
  "source": {
    "./foo.js": "./bar.js",
    "./baz.js": "./yay.js"
  }
}
```

* When compiling from source, alias using glob patterns

```json
{
  "main": "foo.js",
  "source": {
    "./lib/**": "./src/$1"
  }
}
```

The last example allows you to replace your entire lib directory with src so import 'my-module/lib/test.js' would resolve to 'my-module/src/test.js'. You could also use a top-level catch-all pattern like `"**": "./src/$1"` for packages like lodash that have many files in the root to replace (e.g. lodash/cloneDeep with lodash/src/cloneDeep).

---

## File: src/i18n/en/docs/typeScript.md

# TypeScript

_Supported extensions: `ts`, `tsx`_

[TypeScript](https://www.typescriptlang.org/) is a typed superset of JavaScript that compiles down to plain JavaScript, which also supports modern ES2015+ features. Transforming TypeScript works out of the box without any additional configuration.

```html
<!-- index.html -->
<html>
<body>
  <script src="./index.ts"></script>
</body>
</html>
```

```typescript
// index.ts
import message from './message'
console.log(message)
```

```typescript
// message.ts
export default 'Hello, world'
```

## When using React
To use Typescript + React + JSX, you need to:

1. use the `.tsx` extension
2. properly require React
3. use a tsconfig with a [special option](https://www.typescriptlang.org/docs/handbook/jsx.html) `"jsx": "react"`

Full example:
```html
<!-- index.html -->
<html>
<body>
  <div id="root"></div>
  <script src="./index.tsx"></script>
</body>
</html>
```

```typescript
// index.tsx
import React from 'react'
import ReactDOM from 'react-dom'

console.log('Hello from tsx!')

ReactDOM.render(
	<p>Hello</p>,
	document.getElementById('root'),
)
```

```json
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react"
  }
}
```

See this full thread for more details: https://github.com/parcel-bundler/parcel/issues/1199

---

## File: src/i18n/en/docs/vue.md

# Vue

_Supported extensions: `vue`_

---

## File: src/i18n/en/docs/webAssembly.md

# WebAssembly

_Supported extensions: `wasm`_

[WebAssembly](https://webassembly.org) is an emerging technology, but one that will have a huge impact on the web in the near future. Now supported by all major web browsers, as well as Node, WebAssembly will enable a diversity of languages on the web, and not just those that can transpile to JavaScript.

Low-level languages like C and Rust can compile to WebAssembly, which is a binary format for smaller file sizes and faster runtime. Near native-level performance can be had with WebAssembly compiled code, often much faster than equivalent JavaScript. It is likely that we will see JavaScript libraries starting to take advantage of WebAssembly for performance-critical sections of code in the near future.

Parcel makes it **extremely easy** to get started with WebAssembly. Assuming you already have a `.wasm` file (see the next section for an even easier way!), you can just import as usual. Both synchronous and asynchronous imports are supported.

```js
// synchronous import
import { add } from './add.wasm'
console.log(add(2, 3))
// asynchronous import
const { add } = await import('./add.wasm')
console.log(add(2, 3))
```

When synchronously importing a `.wasm` file, Parcel automatically generates extra code to preload the file prior to executing your JavaScript bundle. This means that the binary WebAssembly file is not inlined into your JavaScript as a string, but actually served as a separate binary file as you’d expect. In this way, your code still works synchronously, but Parcel takes care of loading dependencies for you up front.

This is all enabled by Parcel’s internal support for [bundle loaders](https://github.com/parcel-bundler/parcel/pull/565), which are runtime modules which know how to asynchronously load a particular file format. In prior versions, there were hard-coded bundle loaders for JavaScript and CSS, which enabled dynamic import support. In Parcel v1.5.0, this is **completely pluggable** — you can define your own bundle loaders in plugins! This will enable lots of cool functionality in the future for custom binary formats like Glimmer’s binary templates, etc. Super excited to see what this enables!

---

## File: src/i18n/en/docs/webManifest.md

# WebManifest

_Supported extensions: `webmanifest`_

---

## File: src/i18n/en/docs/yaml.md

# YAML

_Supported extensions: `yaml`, `yml`_

---

## File: src/i18n/es/docs/asset_types.md

# 📝 Tipos de Recursos

Como se describe en la [documentación de recursos](assets.html), Parcel representa cada archivo de entrada como un `Asset`. Los tipos de recursos se representan como clases que heredan de la clase base `Asset` e implementan la interfaz requerida para procesar, analizar dependencias, transformar y generar código.

Debido a que Parcel procesa los recursos en paralelo en múltiples núcleos de procesador, las transformaciones que pueden realizar los tipos de recursos están limitadas a las que operan en un solo archivo a la vez. Para transformaciones en varios archivos se puede usar un [Empaquetador](packagers.html) personalizado.

## Interfaz de Recursos

```javascript
const { Asset } = require('parcel-bundler')

class MyAsset extends Asset {
  type = 'foo' // establecer el tipo de salida principal

  parse(code) {
    // convertir el codigo a un AST
    return ast
  }

  pretransform() {
    // opcional. transformar antes de recolectar dependencias.
  }

  collectDependencies() {
    // analizar dependencias
    this.addDependency('my-dep')
  }

  transform() {
    // opcional. transformar después de recolectar dependencias.
  }

  generate() {
    // generar código. Puedes devolver varias representaciones si lo necesitas.
    // los resultados son enviados al empaquetador apropiado para generar los paquetes finales.
    return {
      foo: 'my stuff here', // salida principal
      js: 'some javascript' // representación alternativa para ser colocada en el paquete de JS si es necesario.
    }
  }
}
```

## Registrando un tipo de Recurso

Puedes registrar tus tipos de recursos con un paquete usando el método `addAssetType`. Este acepta una extensión de archivo, y la ruta a tu módulo de tipo de recurso. Esta es una ruta en lugar del objeto real para que pueda ser enviado a procesos paralelos de trabajo.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addAssetType('.ext', require.resolve('./MyAsset'))
```

---

## File: src/i18n/es/docs/assets.md

# 📦 Recursos

Parcel está basado en recursos. Un recurso puede ser cualquier archivo, sin embargo, parcel tiene soporte especial para algunos tipos de archivos como JavaScript, CSS, y HTML. Parcel analiza automáticamente las dependencias a las que se hace referencia en estos archivos y los incluye en el paquete de salida. Recursos similares son agrupados en un mismo paquete de salida. Si importas un tipo de recurso diferente (por ejemplo, si importas un archivo CSS a partir de un archivo JS), empieza la construcción de un segundo archivo y añade una referencia al paquete de salida principal. Esto será demostrado en las próximas secciones.

## JavaScript

El tipo de archivo más común en los empaquetadores web es JavaScript. Parcel soporta tanto CommonJS como módulos en ES6 para importar archivos. También soporta la funcion `import()` para cargar los módulos de manera asíncrona, lo cual se muestra en detalle en la sección [Separación de Código](code_splitting.html).

```javascript
// importa un módulo utilizando CommonJS
const dep = require('./path/to/dep')

// importa un módulo utilizando ES6
import dep from './path/to/dep'
```

También puedes importar otros tipos de recursos que no sean JavaScript desde un archivo JavaScript como por ejemplo CSS o incluso una imagen. Cuando importas alguno de estos tipos de archivos, estos no serán insertados inline como sucede con otros empaquetadores. En vez de eso, este se colocará en un paquete diferente (por ejemplo un archivo CSS) junto con todas sus dependencias. Cuando se usa [CSS Modules](https://github.com/css-modules/css-modules), las clases exportadas serán añadidas al paquete de salida JavaScript. Otros tipos de recursos exportan una URL al paquete de salida JavaScript para que puedas referenciarlo en tu código.

```javascript
// Importa un archivo CSS
import './test.css'

// Importa un archivo CSS con CSS modules
import classNames from './test.css'

// Importa la URL de una imagen
import imageURL from './test.png'
```

Si quieres insertar inline un archivo dentro de un paquete de salida JavaScript, en vez de referenciarlo por su URL, puedes usar el API `fs.readFileSync` de Node.js. La URL debe ser analizada estáticamente, quiere decir, que no pueden contener otras variables (a parte de `__dirname` y `__filename`).

```javascript
import fs from 'fs'

// Lee el contenido como un string
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Lee el contenido como un Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')
```

## CSS

Los archivos CSS pueden ser importados a partir de un archivo JavaScript o HTML, y pueden tener referencias de dependencias utilizando `@import` así también como referencias a imágenes, fuentes, etc, a través de la función `url()`. Otros archivos CSS que fueron importados utilizando `@import` son insertados inline en el mismo paquete CSS, y las referencias usando `url()` son reescritas con sus respectivos nombres. Todos los nombres de los archivos deben ser relativos al archivo CSS actual.

```css
/* Importa otro archivo CSS */
@import './other.css';

.test {
  /* Referencia una imagen */
  background: url('./images/background.png');
}
```

A parte de archivos CSS planos, otros lenguajes que compilan a CSS como LESS, SASS, y Stylus son también soportados, y funcionan de la misma manera.

## SCSS

Para compilar SCSS es necesario el módulo `sass`. Puedes instalarlo usando npm:

```
npm install sass
```

Una vez que tengas `sass` instalado puedes importar tus archivos SCSS desde archivos JavaScript.

```
import './custom.scss'
```

Puedes añadir dependencias a los archivos SCSS usando `@import`.

## HTML

Los archivos HTML son frecuentemente utilizados como punto de entrada para Parcel, pero también pueden ser referenciados en archivos JavaScript, por ejemplo: para proporcionar enlaces a otras páginas. URL a scripts, estilos, multimedia, y otros archivos HTML son extraídos y compilados como se describe arriba. Las referencias son reescritas en el HTML para que sean vinculadas correctamente. Todos los nombres de archivos deben ser relativos al archivo HTML actual.

```html
<html>
<body>
  <!-- referencia a una imagen -->
  <img src="./images/header.png">

  <a href="./other.html">Enlace a otra página</a>

  <!-- Importa un paquete JavaScript -->
  <script src="./index.js"></script>
</body>
</html>
```

---

## File: src/i18n/es/docs/code_splitting.md

# ✂️ Code Splitting

Parcel soporta separación de código sin necesidad de configuración. Esto permite separar el código de tu aplicación en paquetes separados que pueden ser cargados bajo demanda, lo que significa paquetes iniciales de menor tamaño y tiempos de carga más rápido. A medida que el usuario navega por tu aplicación y los módulos son requeridos, Parcel automáticamente se encarga de cargar los demás paquetes bajo demanda.

La separación de código es controlada por la función dinámica [propuesta](https://github.com/tc39/proposal-dynamic-import) `import()`, que funciona como la declaración `import` o la función `require`, con la diferencia de que esta retorna un promesa. Esto significa que el módulo es cargado de forma asíncrona.

El siguiente ejemplo muestra como podrías usar las importaciones dinámicas para cargar una página de tu aplicación bajo demanda.

```javascript
// pages/about.js
export function render() {
  // Renderiza la página
}
```

```javascript
import('./pages/about').then(function(page) {
  // Renderiza la página
  page.render()
})
```

Como `import()` retorna una promesa, también puedes usar async/await. Probablemente necesites configurar Babel para transpilar la sintaxis hasta que este tenga un soporte más amplio en los navegadores.

```javascript
const page = await import('./pages/about')
// Renderiza la página
page.render()
```

Las importaciones dinámicas también se cargan de forma diferida en Parcel, por lo que puedes colocar todas tus llamadas `import()` en la parte de arriba de tu archivo y los paquetes hijos no serán cargados hasta que estos sean utilizados. El siguiente ejemplo muestra como podrías cargar páginas de forma diferida en tu aplicación dinámicamente.

```javascript
// Configuración de un map de nombres de páginas que serán importadas.
// Estas no serán cargadas hasta que sean utilizadas.
const pages = {
  about: import('./pages/about'),
  blog: import('./pages/blog')
}

async function renderPage(name) {
  // Carga de forma diferida la página solicitada.
  const page = await pages[name]
  return page.render()
}
```

**Nota:** Si deseas usar async/await en navegadores que no lo soportan nativamente, recuerda incluir `babel-polyfill` en tu aplicación o `babel-runtime` + `babel-plugin-transform-runtime` en las librerias).

```bash
yarn add babel-polyfill
```

```javascript
import 'babel-polyfill'
import './app'
```

Lee la documentación en [babel-polyfill](http://babeljs.io/docs/usage/polyfill) y [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime).

---

## File: src/i18n/es/docs/getting_started.md

# 🚀 Empezar

Parcel es un empaquetador de aplicaciones web, que se diferencia por la experiencia ofrecida a los desarrolladores. Ofrece un rendimiento ultra-rápido, utilizando procesamiento multinúcleo, y no requiere configuración.

Primero instala Parcel utilizando Yarn or npm:

Yarn:

```bash
yarn global add parcel-bundler
```

npm:

```bash
npm install -g parcel-bundler
```

Crea un archivo package.json en el directorio de su proyecto, usando:

```bash
yarn init -y
```

o

```bash
npm init -y
```

Parcel puede utilizar cualquier tipo de archivo como punto de entrada, pero un archivo HTML o JavaScript es un buen lugar para comenzar. Si enlazas tu archivo JavaScript principal en el HTML usando rutas relativas, entonces Parcel lo procesará por ti, y reemplazará la referencia con una URL al archivo de salida.

A continuación, crea los archivos index.html y index.js.

```html
<html>
<body>
  <script src="./index.js"></script>
</body>
</html>
```

```javascript
console.log('hola mundo')
```

Parcel tiene un servidor de desarrollo embebido, el cual automáticamente reconstruye su aplicación cuando realiza cambios en los archivos, y soporta [reemplazo de módulos en caliente](hmr.html) para desarrollar rápidamente. Solo debes indicar el archivo de entrada:

```bash
parcel index.html
```

Ahora, abre http://localhost:1234/ en su navegador. También puedes reemplazar el puerto por defecto usando la opción `-p `.

Utiliza el servidor de desarrollo cuando no tengas tu propio servidor, o tu aplicación sea completamente renderizada en el lado del cliente. Si cuentas con tu propio servidor, puedes ejecutar Parcel en modo `watch`. Este modo seguirá reconstruyendo la aplicación automáticamente cuando hagas cambios en tus archivos y seguirá soportando reemplazo de módulos en caliente, pero no iniciará un servidor web.

```bash
parcel watch index.html
```

Cuando estes listo para construir tu aplicación para producción, el modo `build` deshabilita el modo `watch` y solo construye la aplicación una vez. Ve la sección [Producción](production.html) para más detalles.

---

## File: src/i18n/es/docs/hmr.md

# 🔥 Reemplazo de Módulos en Caliente

El Reemplazo de Módulos en Caliente (HMR por sus siglas en inglés) mejora la experiencia de desarrollo al actualizar automáticamente los módulos en el navegador en tiempo de ejecución sin necesidad de actualizar toda la página. Esto significa que el estado de la aplicación se puede conservar a medida que cambian cosas pequeñas. La implementación HMR de Parcel soporta tanto archivos JavaScript como CSS sin necesidad de configuración. La funcionalidad HMR es automáticamente deshabilitada cuando se empaqueta la aplicación para un entorno de produción.

Mientras guardas los archivos, Parcel recontruye lo que haya cambiado y envía una actualización a cualquier cliente en ejecución que contenga el código a actualizar. El nuevo código reemplaza la versión antigua, y es re-evaluado con todas sus dependencias. Puedes engancharte a este evento usando el API `module.hot`, el cual puede notificar a tu código cuando un módulo está a punto de ser eliminado, o cuando viene una nueva versión. Proyectos como [react-hot-loader](https://github.com/gaearon/react-hot-loader) ayudan con este proceso, y funcionan sin necesidad de configuración con Parcel.

Hay dos métodos que se deben conocer: `module.hot.accept` y `module.hot.dispose`. El método `module.hot.accept` necesita una función de retorno que será llamada cuando ese módulo o alguna de sus dependencias hayan sido actualizados. Por otro lado `module.hot.dispose` también necesita una función de retorno que será llamada cuando el módulo esté a punto de ser reemplazado.

```javascript
if (module.hot) {
  module.hot.dispose(function() {
    // El módulo está a punto de ser reemplazado
  })

  module.hot.accept(function() {
    // El módulo o alguna de sus dependencias ya fueron actualizadas.
  })
}
```

---

## File: src/i18n/es/docs/how_it_works.md

# 🛠 Cómo funciona

Parcel transforma un árbol de **recursos** en un árbol de **paquetes**. Otros empaquetadores están basados fundamentalmente en recursos JavaScript, con otros formatos añadidos - por ejemplo insertados inline como strings en archivos JS. Parcel es agnóstico con respecto a tipos de archivos - y funcionará con recursos de cualquier tipo en la forma que uno esperaría, sin necesidad de configurarlo. Hay tres pasos en el proceso de empaquetamiento de Parcel.

### 1. Construyendo el árbol de recursos

Parcel toma como entrada un único recurso de partida, que puede ser de cualquier tipo: un archivo JS, HTML, CSS, imágen, etc. Existen varios [tipos de recursos](asset_types.html) definidos en Parcel, cada uno de los cuales saben como manipular determinados tipos de archivos. Los recursos son analizados, sus dependencias extraídas, y luego transformadas a su forma compilada final. Esto genera un árbol de recursos.

### 2. Construyendo el árbol de paquetes

Una vez que el árbol de recursos fue construído, los recursos son ubicados en un árbol de paquetes. Se crea un paquete para el recurso de partida, y para cada `import()` dinámico se crean paquetes hijos, los cuales hacen que ocurra la separación de código.

Cuando se importan recursos de diferente tipo, se crean paquetes adyacentes, por ejemplo si se importa un archivo CSS desde JavaScript, este sería ubicado en un paquete adyacente al paquete correspondiente de JavaScript.

Si un recurso es requerido por más de un paquete, este se eleva hasta el nivel ancestro común más cercano en el árbol de paquetes, para garantizar que no se incluye más de una vez.

### 3. Empaquetado

Luego de que el árbol de paquetes es construído, cada paquete es procesado por un [empaquetador](packagers.html) específico al tipo de archivo, y este se encarga de escribir el paquete en cuestión hacia un archivo. Los empaquetadores saben como combinar el código de cada recurso juntándolos todos en el archivo final que es cargado por el navegador.

---

## File: src/i18n/es/docs/meta.json

{
  "*": {
    "language": "es"
  }
}

---

## File: src/i18n/es/docs/packagers.md

# 📦 Empaquetadores

En Parcel, un `Packager` combina multiples `Asset`s en un paquete de salida final. Esto ocurre en el proceso principal después de que todos los recursos han sido procesados, y un árbol de paquetes ha sido creado. Los `packagers` son registrados en base a un tipo de archivo de salida, y los recursos que generaron ese tipo de salida son enviados a ese packager para la producción del archivo de salida final.

## Interfaz de Packager

```javascript
const { Packager } = require('parcel-bundler')

class MyPackager extends Packager {
  async start() {
    // opcional. escribir cabeceras de archivo si es necesario.
    await this.dest.write(header)
  }

  async addAsset(asset) {
    // requerido. escribir el recurso al archivo de salida.
    await this.dest.write(asset.generated.foo)
  }

  async end() {
    // opcional. escribir el trailer del archivo si es necesario.
    await this.dest.end(trailer)
  }
}
```

## Registro de un Packager

Puedes registrar tu packager con un empaquetador usando el método `addPackager`. Este método acepta un tipo de archivo a registrar, y la ruta a tu módulo packager.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addPackager('foo', require.resolve('./MyPackager'))
```

---

## File: src/i18n/es/docs/plugins.md

# 🔌 Complementos

Parcel adopta un enfoque ligeramente diferente al de muchas otras herramientas, ya que muchos formatos comunes están incluidos por defecto sin la necesidad de instalar y configurar complementos adicionales. Sin embargo, hay casos en los que es posible que desee extender Parcel de una manera no estándar, y para esos momentos, los complementos son compatibles. Los complementos instalados se detectan y cargan automáticamente en función de las dependencias en el archivo `package.json`.

Al agregar soporte para un nuevo formato de archivo, primero debes considerar qué tan extendido está y qué tan estandarizada es la implementación. Si está lo suficientemente extendido y estándar, el formato probablemente debería agregarse al núcleo de Parcel en lugar de ser un complemento que los usuarios necesitan para instalar. Si tienes alguna duda, [GitHub](https://github.com/parcel-bundler/parcel/issues) es el lugar adecuado para debatir.

## API de Complementos

Los complementos de parcel son muy simples. Son módulos que exportan una sola función, que Parcel llama automáticamente durante la inicialización. La función recibe como entrada el objeto `Bundler`, y puede hacer configuraciones tales como el registro de tipos de activos y empaquetadores.

```javascript
module.exports = function(bundler) {
  bundler.addAssetType('ext', require.resolve('./MiActivo'))
  bundler.addPackager('foo', require.resolve('./MiEmpaquetador'))
}
```

Publica este paquete en npm usando el prefijo `parcel-plugin-`, y se detectará y cargará automáticamente como se describe a continuación.

## Usando Complementos

Usar complementos en Parcel no podría ser más simple. Todo lo que necesitas hacer es instalarlos y guardarlos en su `package.json`. Los complementos deben nombrarse con el prefijo `parcel-plugin-`, por ejemplo `parcel-plugin-foo`. Cualquier dependencia enumerada en `package.json` con este prefijo se cargará automáticamente durante la inicialización.

---

## File: src/i18n/es/docs/production.md

# ✨ Producción

Cuando llegue el momento de empaquetar tu aplicación para producción, puedes usar el modo producción de Parcel

```bash
parcel build entry.js
```

Esto deshabilita el modo `watch` y el reemplazo de módulos en caliente, por lo tanto solo se construirá la aplicación una vez. Además, se habilita el minificador para todas las salidas empaquetadas, lo que reduce el tamaño de los archivos. Los minificadores usados por Parcel son [terser](https://github.com/fabiosantoscode/terser) para JavaScript, [cssnano](http://cssnano.co) para CSS, and [htmlnano](https://github.com/posthtml/htmlnano) para HTML.

La habilitación del modo producción también configura la variable de entorno `NODE_ENV=production`. Librerías grandes como React contienen características para depuración que son deshabilitadas al configurar esta variable de entorno, lo que resulta en una construcción más pequeña y rápida para producción.

### Opciones

#### Configurar el directorio de salida

Por defecto: "dist"

```bash
parcel build entry.js --out-dir build/output
o
parcel build entry.js -d build/output
```

```base
root
- build
- - output
- - - entry.js
```

#### Configurar la URL publica en la cual servir

Por defecto: "/"

```bash
parcel build entry.js --public-url ./
```

salida:

```html
<link rel="stylesheet" type="text/css" href="1a2b3c4d.css">
or
<script src="e5f6g7h8.js"></script>
```

#### Deshabilitar la minificacion

Por defecto: minificación habilitada

```bash
parcel build entry.js --no-minify
```

#### Deshabilitar el cache de sistema de archivos

Por defecto: cache habilitado

```bash
parcel build entry.js --no-cache
```

---

## File: src/i18n/es/docs/recipes.md

# 🍰 Recetas

## React

Primero necesitas instalar las dependencias para React.

[Entrada en el blog](http://blog.jakoblind.no/react-parcel/)

```
npm install --save react
npm install --save react-dom
npm install --save-dev parcel-bundler
npm install --save-dev babel-preset-env
npm install --save-dev babel-preset-react
```

<sub>O, si opcionalmente tienes instalado Yarn como gestor de paquetes</sub>

```
yarn add react
yarn add react-dom
yarn add --dev parcel-bundler
yarn add --dev babel-preset-env
yarn add --dev babel-preset-react
```

Luego, asegúrate que la siguiente configuración de Babel esté presente.

```javascript
 // .babelrc
{
  "presets": ["env", "react"]
}
```

Agrega el script de inicio a `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Preact

Primero necesitas instalar las dependencias para Preact.

```
npm install --save preact
npm install --save preact-compat
npm install --save-dev parcel-bundler
npm install --save-dev babel-preset-env
npm install --save-dev babel-preset-preact
```

<sub>O, si opcionalmente tienes instalado Yarn como gestor de paquetes</sub>

```
yarn add preact
yarn add preact-compat
yarn add --dev parcel-bundler
yarn add --dev babel-preset-env
yarn add --dev babel-preset-preact
```

Luego, asegúrate que la siguiente configuración de Babel esté presente.

```javascript
// .babelrc
{
  "presets": ["env", "preact"]
}
```

Agrega el script de inicio a `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

---

## File: src/i18n/es/docs/transforms.md

# 🐠 Transformaciones

Si bien muchos empaquetadores requieren que instales y configures plugins para transformar recursos, Parcel tiene soporte para muchas transformaciones y transpiladores comunes, sin necesidad de instalar ni configurar nada adicional. Puedes transformar JavaScript utilizando [Babel](https://babeljs.io), CSS utilizando [PostCSS](http://postcss.org), y HTML utilizando [PostHTML](https://github.com/posthtml/posthtml). Parcel ejecuta estas transformaciones de manera automática cuando encuentra el archivo de configuración correspondiente (por ejemplo `.babelrc`, `.postcssrc`) en un módulo.

Esto funciona incluso en módulos de terceros dentro de la carpeta `node_modules`: si un archivo de configuración es publicado como parte de un paquete, la transformación correspondiente es habilitada automáticamente, sólo para ese módulo. Esto hace que el empaquetado sea rápido, puesto que sólo se procesan los módulos que necesitan ser transformados. También significa que tú no necesitas configurar manualmente las transformaciones para que incluyan o excluyan determinados archivos, ni necesitas saber cómo está conformado el código de terceros para poder utilizarlo en tu aplicación.

## Babel

[Babel](https://babeljs.io) es un transpilador popular para JavaScript, con un amplio ecosistema de plugins. Usar Babel con Parcel funciona de la misma manera que al usarlo por sí mismo o con otros empaquetadores.

Instala los presets y plugins en tu app:

```bash
yarn add @babel/preset-env
```

Luego, crea un archivo `.babelrc`:

```json
{
  "presets": ["@babel/preset-env"]
}
```

## PostCSS

[PostCSS](http://postcss.org) es una herramienta para transformar CSS con plugins, como [autoprefixer](https://github.com/postcss/autoprefixer), [Preset Env](https://github.com/csstools/postcss-preset-env), y [CSS Modules](https://github.com/css-modules/css-modules). Puedes configurar PostCSS para ser usado con Parcel, creando un archivo de configuración usando uno de estos nombres: `.postcssrc` (JSON), `.postcssrc.js`, o `postcss.config.js`.

Instala los plugins que necesites en tu app:

```bash
yarn add postcss-modules autoprefixer
```

Luego, crea un archivo `.postcssrc`:

```json
{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}
```

Los plugins deben ser declarados en el objeto `plugins` como llaves, y las opciones correspondientes son especificadas usando un objeto como valor de esa llave. Si no hay opciones que especificar para un plugin, simplemente usa `true` como valor.

En el archivo `.browserslistrc` puedes especificar qué navegadores soporta tu app. Esta información es utilizada por Autoprefixer, cssnext y otras herramientas.

```
> 1%
last 2 versions
```

Para habilitar el uso de [CSS Modules](https://github.com/css-modules/css-modules) el procedimiento es ligeramente diferente, usando la llave `modules` en el primer nivel, en lugar de dentro de `plugins`. Esto es debido a que Parcel trata los "CSS Modules" de manera especial, puesto que estos exportan un objeto que debe ser incluido en el paquete de JavaScript. Además necesitas instalar `postcss-modules` en tu proyecto.

## PostHTML

[PostHTML](https://github.com/posthtml/posthtml) es una herramienta para transformar HTML con plugins. Puedes configurar PostHTML con Parcel creando un archivo de configuración usando uno de esos nombres: `.posthtmlrc` (JSON), `.posthtmlrc.js`, o `posthtml.config.js`.

Instala los plugins que necesites en tu app:

```bash
yarn add posthtml-img-autosize
```

Luego, crea un archivo `.posthtmlrc`:

```json
{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}
```

Los plugins deben ser declarados en el objeto `plugins` como llaves, y las opciones correspondientes son especificadas usando un objeto como valor de esa llave. Si no hay opciones que especificar para un plugin, simplemente usa `true` como valor.

## TypeScript

[TypeScript](https://www.typescriptlang.org/) es un superconjunto de JavaScript que añade información de tipos de datos, y que compila a JavaScript simple, y también soporta todas las funcionalidades y sintáxis de ES2015+. Transformar TypeScript funciona sin necesidad de configurar ni instalar nada adicional.

```html
<!-- index.html -->
<html>
  <body>
    <script src="./index.ts"></script>
  </body>
</html>
```

```typescript
// index.ts
import message from './message'
console.log(message)
```

```typescript
// message.ts
export default 'Hello, world'
```

---

## File: src/i18n/fr/docs/api.md

# 📚 API

## Bundler

Au lieu de l'outil en ligne de commande (CLI), vous pouvez également utiliser l'API pour initialiser un empaqueteur (bundler), pour des cas d'utilisation plus avancés (par exemple, un traitement personnalisé après chaque construction).
Un exemple de watch avec chaque option expliquée :

```Javascript
const Bundler = require('parcel-bundler');
const Path = require('path');

// Emplacement du fichier unique en point d'entrée :
const entryFiles = Path.join(__dirname, './index.html');
// OU : Plusieurs fichiers avec un glob (cela peut être aussi un .js)
// const entryFiles = './src/*.js';
// OU : Plusieurs fichiers dans un tableau
// const entryFiles = ['./src/index.html', './un/autre/repertoire/scripts.js'];

// Options de l'empaqueteur
const options = {
  outDir: './dist', // Le répertoire out pour mettre les fichiers construits, par défaut dist
  outFile: 'index.html', // Le nom du fichier en sortie
  publicUrl: './', // L'URL du serveur, par défaut 'dist'
  watch: true, // Surveille les fichiers et les reconstruit lors d'un changement, par défaut pour process.env.NODE_ENV !== 'production'
  cache: true, // Active ou non la mise en cache, la valeur par défaut est true
  cacheDir: '.cache', // Le répertoire où le cache est placé, par défaut .cache
  contentHash: false, // Désactive l'inclusion du hachage de contenu sur le nom du fichier
  global: 'moduleName', // Expose sous ce nom des modules comme UMD, désactivé par défaut
  minify: false, // Minifie les fichiers, activé par défaut si process.env.NODE_ENV === 'production'
  scopeHoist: false, // Active le flag expérimental de scope hoisting/tree shaking, pour des paquets plus petits en production
  target: 'browser', // La cible de compilation : browser/node/electron, par défaut browser
  bundleNodeModules: false, // Les dépendances du package.json ne sont pas incluses lors de l'utilisation de l'option 'node' ou 'electron' avec l'option 'target' ci-dessus. Définissez le à true pour pouvoir les ajouter au paquet, false par défaut
  https: { // Définit une paire personnalisée {key, cert}, utilisez true pour en générer un ou false pour utiliser http
    cert: './ssl/c.crt', // Chemin vers le certificat personnalisé
    key: './ssl/k.key' // Chemin vers la clé personnalisée
  },
  logLevel: 3, // 5 = Tout consigner dans un fichier, 4 = Comme le 3, mais avec des horodatages et également enregistrer les requêtes http sur le serveur de développement, 3 = Consigner les informations, avertissements et erreurs, 2 = Consigner les avertissements et erreurs, 1 = Consigner les erreurs
  hmr: true, // Active ou désactive le HMR lors de la surveillance (watch)
  hmrPort: 0, // Le port sur lequel la socket HMR (Hot Module Reload) fonctionne, par défaut à un port libre aléatoire (0 dans node.js se traduit en un port libre aléatoire)
  sourceMaps: true, // Active ou désactive les sourcemaps, par défaut activé (les constructions minifiées pour l'instant créent toujours des sourcemaps)
  hmrHostname: '', // Un nom d'hôte pour le rechargement de module à chaud, par défaut à ''
  detailedReport: false // Afficher un rapport détaillé des paquets, ressources, tailles des fichiers et durées de build, par défaut à false, les rapports ne sont affichés que si le mode watch est désactivé
};

(async function() {
  // Initialise un empaqueteur (bundler) en utilisant l'emplacement de l'entrée et les options fournies
  const bundler = new Bundler(entryFiles, options);

  // Démarre l'empaqueteur, cela renvoie le paquet principal
  // Utilisez les événements si vous êtes en mode watch, car cette Promise n'est résolue qu'une seule fois et non à chaque reconstruction
  const bundle = await bundler.bundle();
})();
```

Si vous souhaitez utiliser/démarrer le serveur de développement intégré de Parcel, vous pouvez utiliser `bundler.serve()`. Ceci appelle `bundler.bundle()` et lance un simple serveur http (ou https). `serve()` prend 3 arguments (ils sont tous facultatifs), la première est le port, le deuxième est https (il peut s'agir d'un objet `{cert,key}` pointant vers l'emplacement du fichier de key et cert ou `true` pour générer une clé) et le troisième est l'hôte (host).

### Événements

Ceci est une liste de tous les événements d'un empaqueteur

- `bundled` est appelé une seule fois lorsque Parcel a terminé avec succès l'empaquetage. L'instance du [bundle](#bundle) principal est passé à la fonction de rappel

```Javascript
const bundler = new Bundler(...);
bundler.on('bundled', (bundle) => {
  // bundler contient toutes les ressources et tous les paquets, voir la documentation pour plus de détails.
});
// Appelez ceci pour commencer l'empaquetage
bundler.bundle();
```

- `buildEnd` est appelé après chaque construction (**c'est aussi le cas pour chaque reconstruction**), cela est également émis si une erreur s'est produite

```Javascript
const bundler = new Bundler(...);
bundler.on('buildEnd', () => {
  // Faire quelque chose...
});
// Appelez ceci pour commencer l'empaquetage
bundler.bundle();
```

- `buildStart` est appelé au début de la première construction, le tableau `entryFiles` est passé à la fonction de rappel

```Javascript
const bundler = new Bundler(...);
bundler.on('buildStart', entryPoints => {
  // Faire quelque chose...
});
// Appelez ceci pour commencer l'empaquetage
bundler.bundle();
```

- `buildError` est appelé chaque fois qu'une erreur se produit pendant les constructions, l'objet `Error` est passé à la fonction de rappel

```Javascript
const bundler = new Bundler(...);
bundler.on('buildError', error => {
  // Faire quelque chose...
});
// Appelez ceci pour commencer l'empaquetage
bundler.bundle();
```

### Bundle

Un paquet (`Bundle`) est ce que Parcel utilise pour regrouper les ressources ensemble. Il contient également les paquets enfants et frères afin de former une arborescence.

#### Propriétés

- `type`: Le type de ressource qu'il contient (par exemple js, css, map, ...)
- `name`: Le nom du paquet (généré en utilisant `Asset.generateBundleName()` de `entryAsset`)
- `parentBundle`: Le paquet parent, à null dans le cas du paquet d'entrée
- `entryAsset`: Le point d'entrée du paquet, utilisé pour générer le nom et rassembler des ressources.
- `assets`: Un `Set` de toutes les ressources à l'intérieur du paquet
- `childBundles`: Un `Set` de tous les paquets enfants
- `siblingBundles`: Un `Set` de tous les paquets frères
- `siblingBundlesMap`: Un `Map<String(Type: js, css, map, ...), Bundle>` de tous les paquets frères
- `offsets`: Un `Map<Asset, number(line number inside the bundle)>` de tous les emplacements des ressources à l'intérieur, utilisé pour générer des sourcemaps précises

#### Arborescence

Le `Bundle` contient un `parentBundle`, des `childBundles` et des `siblingBundles`, toutes ces propriétés créent ensemble une arborescence de paquets pouvant être parcourue rapidement.

Un exemple très basique d'une arborescence de ressource et l'arborescence de paquets générée

##### Arborescence de ressources :

`index.html` a besoin de `index.js` et `index.css`.

`index.js` a besoin de `test.js` et `test.txt`

```Text
index.html
-- index.js
 |--- test.js
 |--- test.txt
-- index.css
```

##### Arborescence de paquets :

`index.html` est utilisé comme ressource d'entrée pour le paquet principal. Ce paquet principal crée deux paquets enfants : un pour `index.js` et un autre pour `index.css`; car ils sont tous les deux différents du type `html`.

`index.js` a besoin de deux fichiers, `test.js` et `test.txt`.

`test.js` est ajouté aux ressources du paquet `index.js`, car il est du même type que `index.js`

`test.txt` crée un nouveau paquet et est ajouté comme enfant du paquet `index.js`, car son type est différent de `index.js`

`index.css` n'a pas de dépendances et ne contient donc que sa propre entrée.

Les paquets `index.css` et `index.js` sont des paquets frères car ils partagent le même parent.

```Text
index.html
-- index.js (inclut index.js et test.js)
 |--- test.txt (inclut test.txt)
-- index.css (inclut index.css)
```

### Middleware

Le middleware peut être utilisé pour se connecter à un serveur HTTP (par exemple `express` ou `http` de node).

Un exemple d'utilisation du middleware de Parcel avec express

```Javascript
const Bundler = require('parcel-bundler');
const app = require('express')();

const file = 'index.html'; // Passe ici un chemin absolu vers le point d'entrée
const options = {}; // Voir la section des options de la doc de l'api, pour les possibilités

// Initialise un nouveau bundler en utilisant un fichier et des options
const bundler = new Bundler(file, options);

// Permet à express d'utiliser le middelware de bundler, cela permettra à Parcel de gérer chaque requête sur votre serveur express
app.use(bundler.middleware());

// Écoute du port 8080
app.listen(8080);
```

---

## File: src/i18n/fr/docs/asset_types.md

# 📝 Types de ressources

Comme décrit dans la [documentation des ressources](assets.html), Parcel représente chaque fichier en entrée comme un `Asset`. Les types de ressources sont représentés comme des classes héritant de la classe de base `Asset` et implémentant l’interface requise pour analyser, décortiquer les dépendances, transformer et générer le code.

Comme Parcel traite les ressources en parallèle sur plusieurs cœurs de processeurs, les transformations que les types de ressource peuvent effectuer sont limitées à celles qui fonctionnent sur un seul fichier à la fois. Pour les transformations sur plusieurs fichiers, un [Packager](packagers.html) personnalisé peut être utilisé.

## Interface de Asset

```javascript
const {Asset} = require('parcel-bundler');

class MyAsset extends Asset {
  type = 'foo'; // définit le type de sortie principal.

  async parse(code) {
    // analyse le code d'un AST
    return ast;
  }

  async pretransform() {
    // optionnel, transforme avant de collecter les dépendances.
  }

  collectDependencies() {
    // analyse les dépendances
    this.addDependency('my-dep');
  }

  async transform() {
    // optionnel, transforme après avoir collecté les dépendances.
  }

  async generate() {
    // génère le code : vous pouvez retourner plusieurs rendus si nécessaire.
    // Les résultats sont transmis aux packagers appropriés pour générer les paquets finals.
    return [
      {
        type: 'foo',
        value: 'mes trucs ici' // sortie principale
      },
      {
        type: 'js',
        value: 'du javascript' // rendu alternatif à placer dans le paquet JS si nécessaire
        sourceMap
      }
    ];
  }

  async postProcess(generated) {
    // Processus après la génération de tout le code
    // Peut être utilisé pour combiner plusieurs types de ressource
  }
}

module.exports = MyAsset
```

## Enregistrement d'un type d'Asset

Vous pouvez enregistrer votre type de ressource avec un empaqueteur (bundler) en utilisant la méthode `addAssetType`. Elle accepte une extension de fichier à enregistrer et le chemin d'accès à votre module de type de ressource. C'est un chemin plutôt que l'objet réel afin qu'il puisse être transmis aux processus de travail.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addAssetType('.ext', require.resolve('./MonAsset'))
```

---

## File: src/i18n/fr/docs/assets.md

# 📦 Ressources

Parcel est basé sur des ressources. Une ressource peut être n'importe quel fichier, mais Parcel a un support spécial pour certains types de ressources comme les fichiers JavaScript, CSS et HTML. Parcel analyse automatiquement les dépendances référencées dans ces fichiers et les inclut dans le paquet en sortie. Les ressources de types similaires sont regroupées dans le même paquet en sortie. Si vous importez une ressource d'un type différent (par exemple, si vous avez importé un fichier CSS depuis un JS), il commence par créer un paquet enfant et laisse une référence dans le parent. Ceci sera illustré dans les sections suivantes.

Si vous ne parvenez pas à trouver un certain type de ressource dans la documentation, il est possible que la documentation soit obsolète. Pour la liste complète des types de ressource prise en charge, consultez [parcel/src/Parser.js](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/Parser.js#L10).
Pour la liste actuelle des analyseurs, consultez [parcel/src/assets/](https://github.com/parcel-bundler/parcel/tree/master/packages/core/parcel-bundler/src/assets).

Pour tout type de ressources non pris en charge par défaut, vous pouvez vérifier si un plugin existe déjà :

- [Yarn](https://yarnpkg.com/en/packages?q=parcel-plugin-&p=1)
- [npm](https://www.npmjs.com/search?q=parcel-plugin-)
- [awesome-parcel](https://github.com/parcel-bundler/awesome-parcel#plugins)

ou [créez le votre](https://parceljs.org/plugins.html).

---

## File: src/i18n/fr/docs/cli.md

# 🖥 CLI

## Commandes

### Serve

Démarre un serveur de développement, qui reconstruira automatiquement votre application lorsque vous modifiez des fichiers et prend en charge [le remplacement de module à chaud](hmr.html) pour un développement plus rapide.

```bash
parcel index.html
```

### Build

Construit les ressources une seule fois, il active aussi la minification et définit la variable environnement `NODE_ENV=production`. Consultez [Production](production.html) pour plus de détails.

```bash
parcel build index.html
```

_REMARQUE :_ Pour des cas d'utilisation spéciaux, il est également possible d'effectuer une construction unique à partir de l'environnement `development`, comme ceci :

```
NODE_ENV=development parcel build <entrypoint> --no-minify
```

Il crée les mêmes paquets que `serve`, mais il ne surveille pas les ressources, ni les sert.

### Watch

La commande `watch` est similaire à `serve`, sauf que la commande `watch` ne démarre pas un serveur.

```bash
parcel watch index.html
```

### Help

Affiche toutes les options possibles de l'outil en ligne de commande (CLI).

```bash
parcel help
```

### Version

Affiche le numéro de version de Parcel

```bash
parcel --version
```

## Options

### Répertoire de sortie

Par défaut : "dist"

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --out-dir build/output
# ou
parcel build entry.js -d build/output
```

```base
root
- build
- - output
- - - entry.js
```

### Définir l'URL publique à appliquer

Par défaut : "/"

Disponible dans : `serve`, `watch`, `build`

```bash
parcel entry.js --public-url ./dist/
```

Cela produira :

```html
<link rel="stylesheet" type="text/css" href="dist/entry.1a2b3c.css">
<!-- ou -->
<script src="dist/entry.e5f6g7.js"></script>
```

### La cible (target)

Par défaut : browser

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --target node
```

⚠️ `--target node` et `--target electron` n'ajoutent pas les `dependencies` du `package.json` au paquet (mais ajoutent bien les `devDependencies`). Ce comportement peut être modifié via le flag [--bundle-node-modules](#forcer-l'ajout-des-dépendances-node) (voir ci-dessous).

Les cibles possibles sont : `node`, `browser` et `electron`

### Forcer l'ajout des dépendances node

Par défaut : false

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --target node --bundle-node-modules
```

⚠️ Par défaut, les `dependencies` du `package.json` ne sont pas ajoutées au paquet lorsque les options `--target node` ou `--target electron` sont utilisées. `--bundle-node-modules` force leur ajout au paquet.

### Répertoire du cache

Par défaut : ".cache"

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --cache-dir build/cache
```

### Port

Par défaut : 1234

Disponible dans : `serve`

```bash
parcel serve entry.js --port 1111
```

### Changer le niveau de journalisation

Par défaut : 3

Disponible dans : `serve`, `watch`, `build`

```bash
parcel entry.js --log-level 1
```

| Loglevel | Effet                                                                                                   |
| -------- | ------------------------------------------------------------------------------------------------------- |
| 0        | Journal désactivé                                                                                       |
| 1        | Consigner uniquement les erreurs                                                                        |
| 2        | Consigner les erreurs et les avertissements                                                             |
| 3        | Consigner les erreurs, les avertissements et les infos                                                  |
| 4        | Verbose (garder tout dans un log avec l'horodatage  et aussi les requêtes http sur le serveur dev) |
| 5        | Débogue (sauve tout dans un fichier avec l'horodatage)                                                  |

### Nom d'hôte du HMR

Par défaut : `location.hostname` du windows courant

Disponible dans : `serve`, `watch`

```bash
parcel entry.js --hmr-hostname parceljs.org
```

### Port du HMR

Par défaut : Un port disponible au hasard

Disponible dans : `serve`, `watch`

```bash
parcel entry.js --hmr-port 8080
```

### Nom de fichier en sortie

Par défaut : Nom du fichier original

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --out-file output.html
```

Cela modifie le nom du fichier de sortie du paquet

### Imprimer un rapport détaillé

Par défaut : rapport minimal

Disponible dans : `build`

```bash
parcel build entry.js --detailed-report
```

### Désactiver https

Par défaut : https désactivé

Disponible dans : `serve`, `watch` (écoute le HTTPS pour les connexions HMR)

```bash
parcel build entry.js --https
```

⚠️ Cet indicateur génère un certificat auto-signé. Vous devrez peut-être configurer votre navigateur pour autoriser les certificats auto-signés pour localhost.

### Définir un certificat personnalisé

Par défaut : https désactivé

Disponible dans : `serve`, `watch`

```bash
parcel entry.js --cert certificate.cert --key private.key
```

### Ouvrir dans le navigateur

Par défaut : ouverture désactivée

Disponible dans : `serve`

```bash
parcel entry.js --open
```

### Désactiver source-maps

Par défaut : source-maps activé

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --no-source-maps
```

### Désactiver l'installation automatique de dépendances

Par défaut : autoinstall activé

Disponible dans : `serve`, `watch`

```bash
parcel entry.js --no-autoinstall
```

### Désactiver le HMR

Par défaut : HMR activé

Disponible dans : `serve`, `watch`

```bash
parcel entry.js --no-hmr
```

### Désactiver la minification

Par défaut : minification activée

Disponible dans : `build`

```bash
parcel build entry.js --no-minify
```

### Désactiver le cache du système de fichiers

Par défaut : cache activé

Disponible dans : `serve`, `watch`, `build`

```bash
parcel build entry.js --no-cache
```

### Exposer les modules en UMD

Par défaut : désactivé

Disponible dans : `serve`, `watch`, `build`

```bash
parcel serve entry.js --global myvariable
```

### Activer le support expérimental de scope hoisting/tree shaking

Par défaut : désactivé

Disponible dans : `build`

```bash
parcel build entry.js --experimental-scope-hoisting
```

Pour plus d'informations, consultez la [section Tree Shaking](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) de l'article de Devon Govett sur Parcel 1.9.

---

## File: src/i18n/fr/docs/code_splitting.md

# ✂️ Découpage du code

Parcel prend en charge le découpage de code sans aucune configuration. Cela vous permet de diviser le code de votre application en plusieurs paquets pouvant être chargés à la demande, ce qui signifie des paquets initiaux plus petits et des temps de chargement plus rapides. Au fur et à mesure que l'utilisateur navigue dans votre application et que des modules sont nécessaires, Parcel s'occupe de charger automatiquement les paquets enfant à la demande.

Le découpage du code est contrôlé par l'utilisation de la fonction dynamique `import()` décrite par la [proposition de syntaxe](https://github.com/tc39/proposal-dynamic-import), qui fonctionne comme l'instruction normale `import` ou la fonction `require`, mais retourne une promesse. Cela signifie que le module est chargé de manière asynchrone.

## Utilisation des importations dynamiques

L'exemple suivant montre comment utiliser les importations dynamiques pour charger une sous-page de votre application à la demande.

```javascript
// pages/about.js
export function render() {
  // Donne le rendu de la page
}
```

```javascript
import('./pages/about').then(function(page) {
  // Donne le rendu de la page
  page.render()
})
```

## Importations dynamiques avec async/await

Comme `import()` renvoie une promesse, vous pouvez aussi utiliser la syntaxe async/await. Vous aurez probablement besoin de configurer Babel pour transpiler la syntaxe, pour qu'elle soit supportée par la plupart des navigateurs.

```javascript
const page = await import('./pages/about')
// Donne le rendu de la page
page.render()
```

Les importations dynamiques sont également chargées à la volée dans Parcel, donc vous pouvez toujours mettre tous vos appels `import()` en haut de votre fichier et les paquets enfants ne seront pas chargés tant qu'ils ne seront pas utilisés. L'exemple suivant montre comment charger à la volée des sous-pages d'une application.

```javascript
// Configure une map des noms de page pour les importations dynamiques.
// Celles-ci ne sont pas chargées tant qu'elles ne seront pas utilisées
const pages = {
  about: import('./pages/about'),
  blog: import('./pages/blog')
}

async function renderPage(name) {
  // Charge à la volée la page demandée.
  const page = await pages[name]
  return page.render()
}
```

**Remarque :** Si vous souhaitez utiliser async/await dans les navigateurs qui ne le supportent pas nativement, n'oubliez pas d'inclure `babel-polyfill` dans votre application ou `babel-runtime` + `babel-plugin-transform-runtime` en bibliothèques.

```bash
yarn add babel-polyfill
```

```javascript
import 'babel-polyfill'
import './app'
```

Consultez les docs sur [babel-polyfill](http://babeljs.io/docs/usage/polyfill) et [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime).

## Résolution de paquet

Parcel déduit automatiquement l'emplacement des paquets. Ceci est fait dans le module [bundle-url](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/builtins/bundle-url.js) et utilise la stack trace pour déterminer le chemin où le paquet initial a été chargé.

Cela signifie que vous n'avez pas besoin de configurer l'emplacement de chargement des paquets, mais vous devez également les fournir à partir du même emplacement.

Actuellement, Parcel résout les paquets des protocoles suivants : `http`, `https`, `file`, `ftp`, `chrome-extension` et `moz-extension`.

---

## File: src/i18n/fr/docs/coffeeScript.md

# CoffeeScript

_Extensions supportées : `coffee`_

[CoffeeScript](https://coffeescript.org) est un langage qui se transpile en JavaScript, donc cela vous permet d'utiliser une syntaxe plus succincte et d'autres fonctionnalités telles que [l'opérateur existentiel](https://coffeescript.org/#existential-operator), [la syntaxe courte pour regrouper des tableaux](https://coffeescript.org/#slices), [le bloc d'expressions régulières](https://coffeescript.org/#regexes) et bien d'autres.

```coffeescript
# log.coffee
console.log 'Hello there!'
```

```javascript
// index.js
import './log'
```

---

## File: src/i18n/fr/docs/css.md

# CSS

_Extensions supportées : `css`, `pcss`, `postcss`_

Les ressources CSS peuvent être importées à partir d'un fichier JavaScript ou HTML :

```js
import './index.css'
```

```html
<link rel="stylesheet" type="text/css" href="index.css">
```

Les ressources CSS peuvent contenir des dépendances référencées par la syntaxe `@import` ainsi que des références à des images, des polices, etc. via la fonction `url()`. Les autres fichiers CSS, qui sont `@import`és, sont intégrés dans le même paquet CSS, et les références de `url()` sont réécrites en sortie dans leurs noms de fichiers. Tous les noms des fichiers doivent être relatifs au fichier CSS courant.

```css
/* Importe un autre fichier CSS */
@import './other.css';

.test {
  /* Référence un fichier image */
  background: url('./images/background.png');
}
```

En plus des simples CSS, d'autres langages compilés vers CSS comme LESS, SASS et Stylus sont également supportés, et fonctionnent de la même manière.

# PostCSS

[PostCSS](http://postcss.org) est un outil pour transformer du CSS avec des plugins, comme [autoprefixer](https://github.com/postcss/autoprefixer), [Preset Env](https://github.com/csstools/postcss-preset-env), et [CSS Modules](https://github.com/css-modules/css-modules). Vous pouvez configurer PostCSS avec Parcel en créant un fichier de configuration en utilisant l'un de ces noms : `.postcssrc` (JSON), `.postcssrc.js` ou `postcss.config.js`.

Installez les plugins dans votre application :

```bash
yarn add postcss-modules autoprefixer
```

Ensuite, créez un `.postcssrc`:

```json
{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}
```

Les plugins sont spécifiés dans l'objet `plugins` en tant que clés et les options sont définies en utilisant des valeurs d'objet. S'il n'y a pas d'options pour un plugin, définissez-le simplement à `true`.

Les navigateurs ciblés pour Autoprefixer, cssnext et d'autres outils peuvent être spécifiés dans le fichier `.browserslistrc` :

```
> 1%
last 2 versions
```

Les modules CSS sont activés légèrement différemment en utilisant la clé `modules` du niveau supérieur. C'est parce que Parcel doit avoir un support spécial pour les modules CSS car ils exportent un objet à inclure dans le paquet JavaScript. Notez que vous devez toujours installer `postcss-modules` dans votre projet.

## Utilisation avec les bibliothèques CSS existantes

Pour que les modules CSS fonctionnent correctement avec les modules existants, ils doivent spécifier ce support dans leur propre `.postcssrc`.

## Mise en place de la config de minification de cssnano

Parcel ajoute [cssnano](http://cssnano.co) à postcss afin de minifier le css pour la construction en production. La configuration personnalisée peut être définie en créant le fichier `cssnano.config.js` :

```js
module.exports = {
  preset: [
    'default',
    {
      calc: false,
      discardComments: {
        removeAll: true
      }
    }
  ]
}
```

---

## File: src/i18n/fr/docs/elm.md

# Elm

_Extensions supportées : `elm`_

[Elm](https://elm-lang.org/) est un langage fonctionnel doté d'un système de
type avancé qui garantit la correction de votre code et évite les erreurs
d'exécution. Avec son souci de la simplicité et de la rapidité, Elm est un
excellent choix pour créer des applications Web de toutes sortes. Parcel inclus la
prise en charge Elm sans aucune configuration supplémentaire.

```html
<!-- index.html -->

<html>
  <body>
    <main></main>
    <script src="./index.js"></script>
  </body>
</html>
```

```javascript
// index.js

import { Elm } from './Main.elm'

Elm.Main.init({
  node: document.querySelector('main')
})
```

```elm
-- Main.elm

import Browser
import Html exposing (h1, text)

main =
  h1 [] [ text "Hello, Elm!" ]
```

Pour en savoir plus sur Elm et son écosystème d’outils, consultez le
[guide](https://guide.elm-lang.org/) du site officiel.

---

## File: src/i18n/fr/docs/env.md

# 🌳 Variables d'environnement

Parcel utilise [dotenv](https://github.com/motdotla/dotenv) pour charger les variables d'environnement depuis les fichiers `.env`.

Les fichiers `.env` doivent être placés au même endroit que le `package.json` qui contient votre dépendance `parcel-bundler`.

Parcel charge les fichiers `.env` avec ces noms spécifiques pour les valeurs de `NODE_ENV` suivantes :

| Nom de fichier `.env` valide | `NODE_ENV=\*` | `NODE_ENV=test` |
| ---------------------------- | ------------- | --------------- |
| `.env`                       | ✔️            | ✔️              |
| `.env.local`                 | ✔️            | ✖️              |
| `.env.${NODE_ENV}`           | ✔️            | ✔️              |
| `.env.${NODE_ENV}.local`     | ✔️            | ✔️              |

Notamment :

- `NODE_ENV` est par défaut à `development`.
- `.env.local` n'est pas chargé quand `NODE_ENV=test` car [les tests doivent produire les mêmes résultats pour tout le monde](https://github.com/parcel-bundler/parcel/blob/28df546a2249b6aac1e529dd629f506ba6b0a4bb/src/utils/env.js#L9)

---

## File: src/i18n/fr/docs/getting_started.md

# 🚀 Commencer

Parcel est un empaqueteur d'application web, qui se différencie par son expérience de développement. Il offre des performances ultra-rapides grâce au traitement multicœur et ne nécessite aucune configuration.

Commencez par installer Parcel en utilisant Yarn ou npm :

Yarn :

```bash
yarn global add parcel-bundler
```

npm :

```bash
npm install -g parcel-bundler
```

Créez un fichier package.json dans le répertoire de votre projet en utilisant :

```bash
yarn init -y
```

ou

```bash
npm init -y
```

Parcel peut prendre n'importe quel type de fichier comme point d'entrée, mais un fichier HTML ou JavaScript est un bon point de départ. Si vous liez votre fichier JavaScript principal dans le code HTML en utilisant un chemin relatif, Parcel le traitera également pour vous et remplacera la référence par une URL dans le fichier en sortie.

Ensuite, créez un fichier index.html et index.js.

```html
<html>
<body>
  <script src="./index.js"></script>
</body>
</html>
```

```javascript
console.log('hello world')
```

Parcel a un serveur de développement intégré, qui reconstruira automatiquement votre application lorsque vous modifiez des fichiers et il prend en charge un [module de remplacement à chaud](hmr.html) pour un développement plus rapide. Faites-le pointer sur votre fichier d'entrée :

```bash
parcel index.html
```

Maintenant ouvrez http://localhost:1234/ dans votre navigateur. Si le remplacement de module à chaud ne fonctionne pas, vous devez peut-être [configurer votre éditeur](hmr.html#safe-write). Vous pouvez également remplacer le port par défaut avec l'option `-p <numéro de port>`.

Utilisez le serveur de développement lorsque vous n'avez pas votre propre serveur ou si votre application est entièrement exécutée côté client. Si vous avez votre propre serveur, vous pouvez lancer Parcel en mode `watch` à la place. Cela permet de reconstruire automatiquement lorsque les fichiers changent et de prendre en charge le remplacement de module à chaud, mais ne démarre pas un serveur Web.

```bash
parcel watch index.html
```

### Plusieurs fichiers comme point d'entrée

Si vous avez plusieurs fichiers comme point d'entrée, disons `index.html` et `about.html`, vous avez deux façons d'exécuter l'empaqueteur :

En spécifiant les noms des fichiers :

```bash
parcel index.html about.html
```

Utilisez des tokens et créez un glob :

```bash
parcel *.html
```

_REMARQUE :_ Si vous avez une structure de fichier comme celle-ci :

```
- répertoire-1
-- index.html
- répertoire-2
-- index.html
```

La recherche vers http://localhost:1234/répertoire-1/ ne fonctionnera pas, à la place, vous devez indiquer explicitement le fichier http://localhost:1234/répertoire-1/index.html.

### Construction pour la production

Lorsque vous êtes prêt à construire les fichiers finaux utilisés pour la production, le mode `build` arrête de scruter les modifications et ne construit qu'une seule fois. Consultez la section [Production](production.html) pour plus de détails.

### Ajout de Parcel à vos projets

Parfois, il n'est pas possible d'installer Parcel globalement, par exemple si vous utilisez l'agent de génération de quelqu'un d'autre ou si vous souhaitez utiliser un CI pour générer votre projet par programme. Dans ce cas, vous pouvez installer et exécuter Parcel en tant que package local.

Pour l'installer avec Yarn :

```bash
yarn add parcel-bundler --dev
```

Pour l'installer avec NPM:

```bash
npm install parcel-bundler --save-dev
```

Ajoutez ensuite ces scripts de tâches à votre projet, en modifiant votre `package.json`:

```json
{
  "scripts": {
    "dev": "parcel <votre fichier d entrée>",
    "build": "parcel build <votre fichier d entrée>"
  }
}
```

Ensuite, vous pourrez les exécuter:

```bash
# Pour exécuter en mode développment
yarn dev
#ou
npm run dev

# Pour exécuter en mode production
yarn build
#ou
npm run build
```

---

## File: src/i18n/fr/docs/graphQL.md

# GraphQL

_Extensions supportées : `gql`, `graphql`_

---

## File: src/i18n/fr/docs/hmr.md

# 🔥 Remplacement de module à chaud

Le remplacement de module à chaud (Hot Module Replacement : HMR) améliore l'expérience de développement en mettant à jour automatiquement les modules dans le navigateur lors de l'exécution sans nécessiter une actualisation complète de la page. Cela signifie que l'état de l'application peut être conservé lorsque vous changez de petites choses. L'implémentation HMR de Parcel supporte à la fois les ressources JavaScript et CSS. HMR est automatiquement désactivé lors de l'empaquetage en mode production.

Lorsque vous enregistrez des fichiers, Parcel reconstruit les éléments modifiés et envoie une mise à jour contenant le nouveau code à tous les clients en cours d'exécution. Le nouveau code remplace alors l'ancienne version et il est réévalué avec tous les parents. Vous pouvez vous connecter à ce processus en utilisant l'API `module.hot`, qui peut notifier votre code quand un module est sur le point d'être éliminé, ou quand une nouvelle version arrive. Des projets comme [react-hot-loader](https://github.com/gaearon/react-hot-loader) peuvent aider pour ce processus et fonctionnent immédiatement avec Parcel.

Il y a deux méthodes à connaître : `module.hot.accept` et `module.hot.dispose`. Vous appelez `module.hot.accept` avec une fonction de rappel qui est exécutée lorsque ce module ou l'une de ses dépendances sont mis à jour. `module.hot.dispose` accepte une fonction de rappel qui est appelée lorsque ce module est sur le point d'être remplacé.

```javascript
if (module.hot) {
  module.hot.dispose(function() {
    // le module est sur le point d'être remplacé
  })

  module.hot.accept(function() {
    // le module ou l'une de ses dépendances vient d'être mis à jour
  })
}
```

## Dépendances installées automagiquement

Chaque fois que Parcel rencontre une dépendance qui correspond au schéma `node_module` et ne le trouve pas, Parcel tente d'installer cette dépendance en utilisant `yarn` ou `npm` selon la présence ou non d'un fichier `yarn.lock`. Cela évite au développeur de quitter Parcel ou d'avoir plusieurs fenêtres de terminal ouvertes.

Cela ne se produit qu'en _développement_ (en utilisant [`serve`](cli.md#serve) ou [`watch`](cli.md#watch)), par contre en production (en utilisant [`build`](cli.md#build)) autoinstall est désactivé pour empêcher les effets secondaires indésirables sur le déploiement.

Vous pouvez désactiver cette fonctionnalité en utilisant [`--no-autoinstall`](cli.md#désactiver-l'installation-automatique-de-dépendances).

## Safe Write

Certains éditeurs de texte et IDE ont une fonctionnalité appelée `safe write` qui évite la perte de données, en prenant une copie du fichier et en la renommant à l'enregistrement.

Lors de l'utilisation du Hot Module Reload (HMR), cette fonctionnalité bloque la détection automatique des mises à jour de fichiers. Pour désactiver `safe write` utilisez les options fournies ci-dessous :

- `Sublime Text 3` : ajoutez `atomic_save: "false"` à vos préférences utilisateur.
- `IntelliJ` : utilisez la recherche dans les préférences pour trouver "safe write" et désactivez-le.
- `Vim` : ajoutez `:set backupcopy=yes` à vos paramètres.
- `WebStorm` : décochez `Use "safe write"` dans Preferences > Appearance & Behavior > System Settings.

---

## File: src/i18n/fr/docs/how_it_works.md

# 🛠 Comment ça marche

Parcel transforme un arborescence de **ressources** en un arborescence de **paquets**. La plupart des autres empaqueteurs sont fondamentalement basés sur les ressources JavaScript, avec d'autres formats intégrés à l'intérieur - par exemple intégrés en tant que Strings dans les fichiers JS. Parcel est agnostique du type de fichier - il fonctionnera avec n'importe quel type de ressource que vous souhaitez, sans configuration. Le processus d'empaquetage de Parcel comporte trois étapes.

### 1. Construction de l'arborescence des ressources

Parcel prend en entrée un seul élément ressource, qui peut être de n'importe quel type : un fichier JS, HTML, CSS, image, etc. Il y a plusieurs [types de ressources](asset_types.html) définis dans Parcel et il sait comment gérer les types de fichiers spécifiques. Les ressources sont analysés, leurs dépendances sont extraites et elles sont transformées en leur forme finale compilée. Cela crée une arborescence des ressources.

### 2. Construction de l'arborescence des paquets

Une fois que l'arborescence des ressources a été construite, les ressources sont placées dans une arborescence de paquet. Un paquet est créé pour l'élément en entrée et les paquets enfants sont créés pour les `import()` dynamiques, ce qui provoque le découpage du code.

Les paquets d'une fratrie sont créés lorsque les ressources d'un type différent sont importées, par exemple, si vous avez importé un fichier CSS à partir du JavaScript, il sera placé dans un paquet frère au JavaScript correspondant.

Si une ressource est requise dans plusieurs paquets, elle est remontée à l'ancêtre commun le plus proche dans l'arborescence des paquets ainsi elle n'est incluse qu'une fois.

### 3. Empaquetage

Après la construction de l'arborescence des paquets, chaque paquet est écrit dans un fichier par un [packager](packagers.html) spécifique au type de fichier. Les packagers savent comment combiner le code de chaque ressource dans le fichier final chargé par un navigateur.

---

## File: src/i18n/fr/docs/html.md

# HTML

_Extensions supportées : `htm`, `html`_

Une ressource HTML est souvent le fichier d'entrée que vous fournissez à Parcel, mais elle peut aussi être référencée dans des fichiers JavaScript, par exemple pour fournir des liens vers d'autres pages. Les URL des scripts, des styles, des médias et des autres fichiers HTML sont extraites et compilées comme décrit ci-dessus. Les références sont réécrites dans le code HTML afin qu'elles soient liées aux bons fichiers en sortie. Tous les noms de fichiers doivent être relatifs au fichier HTML courant.

```html
<html>
<body>
  <!-- référence un fichier image -->
  <img src="./images/header.png">

  <a href="./other.html">Lien vers une autre page</a>

  <!-- importe un paquet JavaScript -->
  <script src="./index.js"></script>
</body>
</html>
```

## Importation de ressources non compilées

L'ajout de liens vers des fichiers que Parcel peut compiler (par exemple, JavaScript, TypeScript, SCSS, etc.) au format HTML est pris en charge. Parcel traitera automatiquement le fichier et mettra à jour le lien pour qu'il pointe vers la ressource compilé.

```html
<html>
  <head>
    <!-- inclure un fichier SCSS -->
    <link rel="stylesheet" href="./my-styles/style.scss">
  </head>
</html>
```

# PostHTML

[PostHTML](https://github.com/posthtml/posthtml) est un outil pour transformer du HTML avec des plugins. Vous pouvez configurer PostHTML avec Parcel en créant un fichier de configuration en utilisant l'un de ces noms : `.posthtmlrc` (JSON), `.posthtmlrc.js` ou `posthtml.config.js`.

Installez des plugins dans votre application :

```bash
yarn add posthtml-img-autosize
```

Ensuite, créez un `.posthtmlrc`:

```json
{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}
```

Les plugins sont spécifiés dans l'objet `plugins` en tant que clés, et les options sont définies en utilisant des valeurs d'objets. S'il n'y a pas d'options pour un plugin, définissez-le simplement à `true`.

---

## File: src/i18n/fr/docs/javascript.md

# JavaScript

_Extensions supportées : `js`, `jsx`, `es6`, `jsm`, `mjs`_

Le type de fichier le plus traditionnel pour les empaqueteurs web, c'est le JavaScript. Parcel prend en charge la syntaxe CommonJS et les modules ES6 pour l'importation de fichiers. Il prend également en charge la syntaxe de la fonction dynamique `import()` pour charger les modules de manière asynchrone, qui est expliquée dans la section [Découpage du code](code_splitting.html). Les importations dynamiques peuvent également importer des modules à partir d'URL.

```javascript
// Importe un module en utilisant la syntaxe CommonJS
const dep = require('./path/to/dep')

// Importe un module ES6
import dep from './path/to/dep'

// Importe un module depuis une URL (par exemple CDN) et utilisant l'importation dynamique
import('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js').then(() => {
  console.log(_.VERSION)
})
```

Vous pouvez également importer des éléments non JavaScript à partir d'un fichier JavaScript, par exemple du CSS, du HTML ou même un fichier image. Lorsque vous importez l'un de ces fichiers, il n'est pas intégré comme dans d'autres empaqueteurs. Au lieu de cela, Parcel le place dans un paquet séparé (par exemple un fichier CSS) avec toutes ses dépendances. Lors de l'utilisation des [Modules CSS](https://github.com/css-modules/css-modules), les classes exportées sont placées dans le paquet JavaScript. Les autres types de ressources exportent une URL vers le fichier en sortie dans le paquet JavaScript afin que vous puissiez les référencer dans votre code.

```javascript
// Importe un fichier CSS
import './test.css'

// Importe un fichier CSS avec Modules CSS
import classNames from './test.css'

// Importe l'URL d'un fichier image
import imageURL from './test.png'

// Importe un fichier HTML
import('./some.html')
// ou :
import html from './some.html'
// ou :
require('./some.html')
```

Si vous souhaitez insérer un fichier dans le paquet JavaScript au lieu de le référencer par une URL, vous pouvez utiliser l'API `fs.readFileSync` de Node.js à cet effet. L'URL doit pouvoir être analysée statiquement, ce qui signifie qu'elle ne peut contenir aucune variable (autre que `__dirname` et `__filename`).

```javascript
import fs from 'fs'

// Lit le contenu comme un String
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Lit le contenu comme un Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')

// Convertit le contenu du buffer en image
;<img src={`data:image/png;base64,${buffer.toString('base64')}`} />
```

### Images dans JSX

Vous trouverez ci-dessous un exemple d’importation d’un fichier image à utiliser dans JSX.

```js
// Importe le fichier image
import megaMan from "./images/mega-man.png";

// JSX
<img src={megaMan} title="Mega Man" alt="Mega Man" />

// JSX (avec un chemin personnalisé)
<img src={`/dist${megaMan}`} title="Mega Man" alt="Mega Man" />
```

# Babel

[Babel](https://babeljs.io) est un transpileur populaire pour JavaScript, avec un grand écosystème de plugin. L'utilisation de Babel avec Parcel fonctionne de la même manière que l'utilisation autonome ou avec d'autres empaqueteurs.

Installez les presets et les plugins dans votre application :

```shell
yarn add @babel/preset-react
```

Ensuite, créez un `.babelrc`:

```json
{
  "presets": ["@babel/preset-react"]
}
```

Vous pouvez aussi mettre la config de `babel` dans le `package.json`

```json
"babel": {
  "presets": ["@babel/preset-react"]
}
```

REMARQUE : `package.json` est prioritaire sur `.babelrc`.

## Transformations Babel par défaut

Parcel transpile par défaut votre code avec `@babel/preset-env`, ceci transpile chaque module interne (requires locaux) et externe (node_modules) pour correspondre à la cible définie.

Pour la cible `browser`, il utilise [browserslist](https://github.com/browserslist/browserslist), la browserlist cible peut être définie dans le fichier `package.json` (`engines.browsers` ou `browserslist`) ou en utilisant un fichier de configuration (`browserslist` ou `.browserslistrc`).

Par défaut, la browserlist cible est à : `> 0,25%` (ce qui signifie que tous les navigateurs ayant 0,25% ou plus du nombre total d'utilisateurs Web actifs sont pris en charge)

Pour la cible `node`, Parcel utilise le `engines.node` défini dans `package.json`, la valeur par défaut est _node 8_.

# Flow

[Flow](https://flow.org/) est un vérificateur populaire de type statique pour JavaScript. L'utilisation de Flow avec Parcel est aussi simple que de placer `// @flow` comme première ligne de vos fichiers `js`.

Parcel installera automatiquement la configuration Babel requise pour séparer les types de Flow de la sortie compilée. Vous n'avez donc rien à craindre à l'exception des [intégrations de l'éditeur](https://flow.org/en/docs/editors/) ou de la prise en charge du [module de résolution des chemins absolus](module_resolution.html#flow-avec-la-résolution-de-chemin-absolu-et-tilde) avec `.flowconfig`.

---

## File: src/i18n/fr/docs/json.md

# JSON

_Extensions supportées : `json`, `json5`_

---

## File: src/i18n/fr/docs/less.md

# LESS

_Extensions supportées : `less`_

Il n'est même pas nécessaire d'installer less 😱, parcel installera automatiquement less s'il détecte un fichier less.

Vous pouvez importer des fichiers LESS depuis des fichiers JavaScript ou HTML.

```javascript
import './custom.less'
```

ou

```html
<link href="./custom.less" rel="stylesheet">
```

---

## File: src/i18n/fr/docs/meta.json

{
  "*": {
    "language": "fr"
  }
}

---

## File: src/i18n/fr/docs/module_resolution.md

# 📔 Résolution de module

Le résolveur de Parcel implémente une version modifiée de l'algorithme de [résolution des node_modules](https://nodejs.org/api/modules.html#modules_all_together).

## Résolution de module

En plus de l'algorithme standard, tous les [types de ressources supportés par Parcel](assets.html) sont aussi résolus.

La résolution de module peut être relative à la :

- **racine de l'entrée** : le répertoire du point d'entrée spécifié à Parcel ou la racine partagée (répertoire parent commun) lorsque plusieurs points d'entrée sont spécifiés.
- **racine du package** : le répertoire racine du module le plus proche dans `node_modules`.

### Chemins absolus

`/foo` résout `foo` relatif à la **racine de l'entrée**.

### Chemins du tilde ~

`~/foo` résout `foo` relatif à la **racine du package** le plus proche ou, s'il ne trouve pas, à la **racine de l'entrée**.

### Chemins de fichiers glob

Les globs sont des importations génériques qui regroupent plusieurs ressources à la fois. Les globs peuvent correspondre à tout ou une partie des fichiers (`/assets/*.png`), ainsi qu'aux fichiers de plusieurs répertoires (`/assets/**/*`).

Cet exemple regroupe un répertoire de fichiers png et renvoie l’URL dist.

```
import foo from "/assets/*.png";
// {
//   'file-1': '/file-1.8e73c985.png',
//   'file-2': '/file-1.8e73c985.png'
// }
```

### Le champs `browser` de package.json

Si un package inclut un [champs package.browser](https://docs.npmjs.com/files/package.json#browser), Parcel l'utilisera à la place de l'entrée package.main.

### Alias

Les alias sont supportés via le champ `alias` dans `package.json`.

Ces exemples d'alias `react` vers `preact` et d'un module local personnalisé qui ne sont pas dans `node_modules`.

```json
// package.json
{
  "name": "some-package",
  "devDependencies": {
    "parcel-bundler": "^1.7.0"
  },
  "alias": {
    "react": "preact-compat",
    "react-dom": "preact-compat",
    "local-module": "./custom/modules"
  }
}
```

Évitez d'utiliser des caractères spéciaux dans vos alias, car certains peuvent être utilisés par Parcel et d'autres par des outils ou des extensions tiers. Par exemple :

- `~` utilisé par Parcel pour résoudre les [chemins du tilde](#chemins-du-tilde-~).
- `@` utilisé par npm pour résoudre les organisations de npm.

Nous vous conseillons d'être explicite lors de la définition de vos alias, veuillez donc **spécifier les extensions de fichier**, sinon Parcel devra le deviner. Consultez [Export nommés de JavaScript](#export-nommés-de-javascript) pour voir un exemple.

## Problèmes communs

### Export nommés de JavaScript

Les cartographies d'alias s'appliquent à de nombreux types d'actifs, mais ne prennent pas spécifiquement en charge la cartographie des exports nommées de JavaScript. Si vous souhaitez cartographier les exports nommées JS, vous pouvez le faire ainsi :

```json
// package.json
{
  "name": "some-package",
  "alias": {
    "ipcRenderer": "./electron-ipc.js" // specifiez une extension de fichier
  }
}
```

et réexporter l'export nommé dans le fichier aliasé :

```js
// electron-ipc.js
module.exports = require('electron').ipcRenderer
```

### Flow avec la résolution de chemin absolu et tilde

Lorsque vous utilisez la résolution de module de chemin absolu ou tilde, vous devez configurer Flow à l'aide de [module.name_mapper](https://flow.org/en/docs/config/options/#toc-module-name-mapper-regex-string).

Soit un projet avec cette structure :

```
package.json
.flowconfig
src/
  index.html
  index.js
  components/
    apple.js
    banana.js
```

Où `src/index.html` est le point d'entrée, notre **racine de l'entrée** est le répertoire `src/`.

Donc cela mappe correctement les éléments suivants :

```javascript
// index.js
import Apple from '/components/apple'
```

Nous avons besoin que Flow remplace le chemin actuel `/` en `'/components/apple'` avec `src/`, cela se traduit en `'src/components/apple'`.

Le paramètre suivant dans notre `.flowconfig` réalise ce remplacement :

```
[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/src/\1'
```

Où `` est un identifiant spécifique à Flow indiquant l'emplacement de notre `.flowconfig`.

REMARQUE : `module.name_mapper` peut avoir plusieurs entrées. Cela permet de prendre en charge la résolution du chemin [Absolu](module_resolution.html#chemins-absolus) ou [Tilde](module_resolution.html#chemins-du-tilde-~) en plus du support de l'[alias du module local](module_resolution.html#alias).

### Résolution TypeScript ~

TypeScript devra connaître votre utilisation de la résolution de module `~` ou les cartographies d'alias. Veuillez vous reporter à la documentation de [TypeScript Module Resolution docs](https://www.typescriptlang.org/docs/handbook/module-resolution.html) pour plus d'informations.

```json
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~*": ["./src/*"]
    }
  }
}
```

### Résolution Monorepo

Ce sont en ce moment les utilisations conseillées avec des monorepos :

Utilisation conseillée :

- utilisez les chemins relatifs.
- utilisez `/` pour un chemin racine si une racine est requise.

Utilisation déconseillée :

- **évitez** l'utilisation de `~` dans les monorepos.

Si vous êtes un utilisateur de monorepo et que vous souhaitez contribuer à ces recommandations, veuillez fournir des exemples de repos lors de l'ouverture d'issue pour aider la discussion.

---

## File: src/i18n/fr/docs/openGL.md

# OpenGL Shading Language (GLSL)

_Extensions supportées : `glsl`, `vert`, `frag`_

---

## File: src/i18n/fr/docs/packagers.md

# 📦 Packagers

Dans Parcel, un `Packager` combine plusieurs `Asset` ensemble dans un paquet final en sortie. Cela se produit dans le processus principal après que toutes les ressources ont été traitées et qu'une arborescence du paquet a été créé. Les packagers sont enregistrés en fonction du type de fichier de sortie et les ressources générées par ce type de sortie sont envoyées à ce packager pour la production finale du fichier en sortie.

## Packager Interface

```javascript
const { Packager } = require('parcel-bundler')

class MyPackager extends Packager {
  async start() {
    // optionnel. Ecrit l'entête du fichier si besoin.
    await this.dest.write(header)
  }

  async addAsset(asset) {
    // obligatoire. Ecrit la ressource dans le fichier de sortie.
    await this.dest.write(asset.generated.foo)
  }

  async end() {
    // optionnel. Ecrit la fin du fichier si besoin.
    await this.dest.end(trailer)
  }
}

module.exports = MyPackager
```

## Enregistrement d'un packager

Vous pouvez enregistrer votre packager avec un empaqueteur (bundler) en utilisant la méthode `addPackager`. Il accepte un type de fichier pour s'enregistrer et le chemin vers votre module packager.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addPackager('foo', require.resolve('./MonPackager'))
```

---

## File: src/i18n/fr/docs/plugins.md

# 🔌 Plugins

Parcel adopte une approche légèrement différente de beaucoup d'autres outils dans la mesure où de nombreux formats courants sont inclus sans avoir besoin d'installer et de configurer des plugins supplémentaires. Cependant, il y a des cas où vous auriez besoin d'étendre Parcel d'une manière non standard, et pour ces cas, les plugins sont supportés. Les plugins installés sont automatiquement détectés et chargés en fonction des dépendances du `package.json`.

Lors de l'ajout du support pour un nouveau format de fichier à Parcel, vous devez d'abord considérer à quel point il est répandu et comment la mise en œuvre est standardisée. S'il est suffisamment répandu et standard, le format devra probablement être ajouté au cœur de Parcel au lieu d'un plugin que les utilisateurs devront installer. Si vous avez des doutes, [GitHub](https://github.com/parcel-bundler/parcel/issues) est le bon endroit pour en discuter.

## API du plugin

Les plugins de Parcel sont très simples. C'est simplement des modules qui exportent une seule fonction, qui est appelée automatiquement par Parcel lors de l'initialisation. La fonction reçoit en entrée l'objet `Bundler` et peut faire la configuration telle que l'enregistrement des types de ressource et des packagers.

```javascript
module.exports = function(bundler) {
  bundler.addAssetType('ext', require.resolve('./MonAsset'))
  bundler.addPackager('foo', require.resolve('./MonPackager'))
}
```

Publiez ce paquet sur npm en utilisant les préfixes `parcel-plugin-` ou `@votre-scope/parcel-plugin-` et il sera automatiquement détecté et chargé comme décrit ci-dessous.

## Utilisations des Plugins

L'utilisation de plugins dans Parcel ne pouvait pas être plus simple. Tout ce que vous avez à faire est de les installer et de les enregistrer dans votre `package.json`. Les plugins doivent être nommés avec les préfixes `parcel-plugin-` ou `@votre-scope/parcel-plugin-`, par exemple `parcel-plugin-foo` ou `@votre-scope/parcel-plugin-foo`. Toutes les dépendances répertoriées dans `package.json` avec ces préfixes seront automatiquement chargés lors de l'initialisation.

---

## File: src/i18n/fr/docs/production.md

# ✨ Production

Quand vient le temps d'empaqueter votre application pour la production, vous pouvez utiliser le mode de production de Parcel.

```bash
parcel build entry.js
```

## Optimisations

Cela désactive le mode watch et le remplacement de module à chaud, de sorte qu'il ne sera construit qu'une seule fois. Cela permet également de minifier tous les paquets en sortie pour réduire la taille du fichier. Les minifieurs utilisés par Parcel sont [terser](https://github.com/fabiosantoscode/terser) pour JavaScript, [cssnano](http://cssnano.co) pour CSS et [htmlnano](https://github.com/posthtml/htmlnano) pour HTML.

L'activation du mode production définit également la variable d'environnement `NODE_ENV=production`. Les grandes bibliothèques comme React ont des fonctionnalités de débogage uniquement pour le développement qui sont désactivées en définissant cette variable d'environnement, ce qui se traduit par des constructions plus petites et plus rapides pour la production.

Pour tirer parti du même type de fonctionnalités de débogage réservé uniquement au développement, assurez-vous que [l'option `dead_code` de terser](https://github.com/terser-js/terser#compress-options) soit mise (elle l'est par défaut) et enveloppez tout le développement uniquement en débogage dans un contrôle conditionnel comme suit :

```js
if (process.env.NODE_ENV === 'development') {
  // Ou, `process.env.NODE_ENV !== 'production'`
  // S'exécute seulement en développement et sera supprimé de la version de production
}
```

## Stratégie de nommage des fichiers

Pour permettre à votre cdn de définir des règles de mise en cache très agressives, afin d'avoir une performance et une efficacité optimale, Parcel hache les noms de fichier de la plupart des paquets (selon si le paquet doit avoir un nom lisible/mémorisable ou non, principalement pour le référencement).

Parcel suit le tableau suivant, lorsqu’il s’agit de nommer des paquets. (Les points d'entrée ne sont jamais hachés)

|                     Type de bundle | Type               | Contenu haché |
| ---------------------------------: | ------------------ | :-----------: |
|                               Tous | point d'entrée     |      ❌       |
|                         JavaScript | `<script>`         |      ✅       |
|                         JavaScript | Import dynamique   |      ❌       |
|                         JavaScript | Service worker     |      ❌       |
|                               HTML | iframe             |      ❌       |
|                               HTML | lien d'ancrage     |      ❌       |
| Brut (Images, fichiers texte, ...) | Import/Require/... |      ✅       |

Le hachage du fichier suit le modèle de dénomination suivant : `<nom du répertoire>-<hash>.<extension>`

## Les pièges du multiplateforme

Afin d'optimiser les performances de construction de la production, Parcel essayera de déterminer le nombre de processeurs disponibles sur la machine qui exécute la commande build pour distribuer le travail en conséquence. Pour ce faire, Parcel s'appuie sur la bibliothèque [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count).

Cela suppose que vous ayez le programme [`lscpu`](http://manpages.courier-mta.org/htmlman1/lscpu.1.html) disponible sur votre système.

## Utilisation d'un CI

Si vous souhaitez intégrer Parcel à votre système d'intégration continue (par exemple Travis ou Circle CI), vous devrez peut-être installer Parcel en tant que dépendance locale.

Les instructions se [trouvent ici](getting_started.html#ajout-de-parcel-à-vos-projets).

---

## File: src/i18n/fr/docs/pug.md

# Pug

_Extensions supportées : `jade`, `pug`_

---

## File: src/i18n/fr/docs/reasonML.md

# ReasonML

_Extensions supportées : `ml`, `re`_

## ReasonML/BuckleScript

[ReasonML](https://reasonml.github.io/) compile du OCaml en JavaScript à l'aide de [BuckleScript](https://bucklescript.github.io). Vous pouvez utiliser ReasonML en installant des dépendances et en créant `bsconfig.json` :

```bash
$ yarn add bs-platform --dev
```

```json
// bsconfig.json
// from https://github.com/BuckleScript/bucklescript/blob/master/jscomp/bsb/templates/basic-reason/bsconfig.json

{
  "name": "whatever",
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```html
<!-- index.html -->
<!doctype html>
<html>
<body>
  <script src="./src/index.re"></script>
</body>
</html>
```

```reason
/* src/index.re */
print_endline("Hello World");
```

### ReasonReact

[ReasonReact](https://reasonml.github.io/reason-react/) est une liaison de React pour ReasonML. Vous pouvez l'utiliser aussi avec Parcel :

```bash
$ yarn add react react-dom reason-react
```

```diff
// bsconfig.json

{
  "name": "whatever",
+ "reason": {
+   "react-jsx": 2
+ },
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [
+   "reason-react"
  ],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```diff
<!-- index.html -->
<html>
<body>
+  <div id="app"></div>
  <script src="./src/index.re"></script>
</body>
</html>
```

```reason
/* src/Greeting.re */

let component = ReasonReact.statelessComponent("Greeting");

let make = (~name, _children) => {
  ...component,
  render: _self => <div> (ReasonReact.string("Hello! " ++ name)) </div>,
};
```

```reason
/* src/index.re */

ReactDOMRe.renderToElementWithId(<Greeting name="Parcel" />, "app");
```

---

## File: src/i18n/fr/docs/recipes.md

# 🍰 Recettes

## React

D'abord nous avons besoin d'installer les dépendances pour React.

[Article du blog](http://blog.jakoblind.no/react-parcel/)

```bash
npm install --save react
npm install --save react-dom
npm install --save-dev parcel-bundler
```

<sub>Ou si vous avez installé le gestionnaire de paquets Yarn</sub>

```bash
yarn add react
yarn add react-dom
yarn add --dev parcel-bundler
```

Ajoutez un script de démarrage à `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Preact

D'abord vous avez besoin d'installer les dépendances pour Preact.

```bash
npm install --save preact
npm install --save preact-compat
npm install --save-dev parcel-bundler
npm install --save-dev babel-preset-preact
```

<sub>Ou si vous avez installé le gestionnaire de paquets Yarn</sub>

```bash
yarn add preact
yarn add preact-compat
yarn add --dev parcel-bundler
yarn add --dev babel-preset-preact
```

Ensuite, assurez-vous que la configuration Babel suivante est présente.

```javascript
// .babelrc
{
  "presets": [
    "preact"
 ]
}
```

Ajoutez un script de démarrage à `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Vue

D'abord vous avez besoin d'installer les dépendances pour Vue.

```bash
npm install --save vue
npm install --save-dev parcel-bundler
```

<sub>Ou si vous avez installé le gestionnaire de paquets Yarn</sub>

```bash
yarn add vue
yarn add --dev parcel-bundler
```

Ajoutez un script de démarrage à `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Typescript

D'abord installez les dépendances pour Typescript

```bash
npm install --save-dev typescript
npm install --save-dev parcel-bundler
```

<sub>Ou si vous avez installé le gestionnaire de paquets Yarn</sub>

```bash
yarn add typescript --dev
yarn add --dev parcel-bundler
```

### Utiliser directement un fichier typescript depuis index.html

Ensuite, ajoutez le script `start` de démarrage au `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

Puis, dans votre fichier `index.html`, importez directement le fichier `.ts`.

```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <!-- Ici 👇 -->
    <script src="./myTypescriptFile.ts"></script>
</body>
</html>
```

C'est tout!

### Compiler directement le fichier `.ts`

Ajoutez le script `start` de démarrage au `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel myTypescriptFile.ts"
}
```

Fini! 😄 Le fichier `.js` compilé se trouve dans dossier `dist`.

---

## File: src/i18n/fr/docs/rust.md

# Rust

_Extensions supportées : `rs`_

[Rust](https://www.rust-lang.org) est un langage de programmation système développé par Mozilla, qui offre des performances natives avec des caractéristiques de sécurité de la mémoire et des threads intéressantes. Rust a récemment ajouté la prise en charge de la compilation à WebAssembly, et maintenant Parcel **facilite grandement** le démarrage avec zéro configuration !

Maintenant, vous pouvez simplement importer des fichiers `.rs` comme n'importe quel autre type de fichier dans Parcel ! En supposant que [Rustup](https://rustup.rs) soit installé, Parcel **prend automatiquement soin d’installer** les bonnes chaînes d’outils, les cibles et les autres prérequis de construction. Il fonctionne avec les projets [Cargo](https://github.com/rust-lang/cargo), ainsi qu'avec les fichiers source Rust. Il piste automatiquement vos dépendances afin que les **fichiers soient surveillés** et que les reconstructions se produisent lorsque vous enregistrez et bien plus encore !

Comme avec les fichiers `.wasm`, les fichiers `.rs` peuvent être importés avec des importations synchrones ou asynchrone.

```js
// import synchrone
import { add } from './add.rs'
console.log(add(2, 3))
// import asynchrone
const { add } = await import('./add.rs')
console.log(add(2, 3))
```

Du côté de Rust, vous devez simplement vous assurer que les noms de fonctions ne sont pas déformés et sont publics.

```rs
#[no_mangle]
pub fn add(a: i32, b: i32) -> i32 {
  return a + b
}
```

---

## File: src/i18n/fr/docs/scss.md

# SCSS

_Extensions supportées : `sass`, `scss`_

La compilation SCSS nécessite un module `sass` (une version JS `dart-sass`). Pour l'installer avec npm :

```bash
npm install -D sass
```

Une fois que vous avez installé `sass`, vous pouvez importer des fichiers SCSS à partir de fichiers JavaScript.

```javascript
import './custom.scss'
```

Les dépendances dans les fichiers SCSS peuvent être utilisées avec les instructions `@import`.

Si vous n'avez pas de module `sass` installé avant l'exécution de Parcel, Parcel l'installera automatiquement pour vous.

**Remarques :** Vous pouvez aussi utiliser le module `node-sass` pour la compilation du SCSS. L'utilisation du module `node-sass` vous donnera une compilation plus rapide. Cependant, [une issue](https://github.com/parcel-bundler/parcel/issues/1836) a été reportée sur l'utilisation du module `node-sass` avec Parcel.

---

## File: src/i18n/fr/docs/stylus.md

# Stylus

_Extensions supportées : `styl`_

Il n'est même pas nécessaire d'installer Stylus 😱, parcel installera automatiquement Stylus s’il détecte un fichier Stylus.

Vous pouvez importer des fichiers Stylus à partir de fichiers JavaScript ou html.

```javascript
import './custom.styl'
```

ou

```html
<link href="./custom.styl" rel="stylesheet">
```

---

## File: src/i18n/fr/docs/toml.md

# TOML

_Extensions supportées : `toml`_

---

## File: src/i18n/fr/docs/transforms.md

# 🐠 Transformations

Alors que de nombreux empaqueteurs vous demandent d'installer et de configurer des plugins pour transformer les ressources, Parcel a un support prêt à l'emploi pour de nombreuses transformations et transpileurs. Vous pouvez transformer du JavaScript en utilisant [Babel](https://babeljs.io), du CSS à l'aide de [PostCSS](http://postcss.org) et du HTML en utilisant [PostHTML](https://github.com/posthtml/posthtml). Parcel exécute automatiquement ces transformations lorsqu'il trouve un fichier de configuration (par exemple `.babelrc`, `.postcssrc`) dans un module. (En plus de toutes les transformations spécifiées dans `.babelrc`, Parcel utilise toujours Babel sur tous les modules compilés en JavaScript moderne pour qu'ils soient pris en charge par tous les navigateurs. Consultez la section [JavaScript/Default Babel Transforms](javascript.html#transformations-babel-par-défaut) pour plus d'informations.)

## Modules tiers

Les fichiers de configuration (comme `.babelrc`) ne s’appliqueront pas par défaut aux fichiers à l'intérieur des `node_modules` tiers. Cependant, si le répertoire du module est lié symboliquement (comme cela est courant dans certaines conventions monorepo) et le `package.json` du module a le champ `source` défini, alors les fichiers de configuration à l’intérieur du répertoire du module seront respectés. Voici les types de valeurs supportées par le champ `source` :

- Traite tous les fichiers dans le code source, ne change pas la résolution

```json
{
  "main": "foo.js",
  "source": true
}
```

- Lors de la compilation du source, il utilise bar.js comme point d'entrée

```json
{
  "main": "foo.js",
  "source": "bar.js"
}
```

- Lors de la compilation du source, il utilise les fichiers spécifiés

```json
{
  "main": "foo.js",
  "source": {
    "./foo.js": "./bar.js",
    "./baz.js": "./yay.js"
  }
}
```

- Lors de la compilation du source, il utilise les modèles glob

```json
{
  "main": "foo.js",
  "source": {
    "./lib/**": "./src/$1"
  }
}
```

Le dernier exemple vous permet de remplacer l'intégralité de votre répertoire lib par src afin que l'importation de 'my-module/lib/test.js' soit résolue en 'my-module/src/test.js'. Vous pouvez également utiliser un modèle de niveau supérieur fourre-tout comme `"**": "./src/$1"` pour les packages comme lodash qui ont beaucoup de fichiers à remplacer à la racine (par exemple lodash/cloneDeep par lodash/src/cloneDeep).

---

## File: src/i18n/fr/docs/typeScript.md

# TypeScript

_Extensions supportées : `ts`, `tsx`_

[TypeScript](https://www.typescriptlang.org/) est un sur-ensemble typé du JavaScript qui compile en JavaScript simple, qui prend également en charge les fonctionnalités modernes ES2015+. La transformation TypeScript fonctionne sans aucune configuration supplémentaire.

```html
<!-- index.html -->
<html>
<body>
  <script src="./index.ts"></script>
</body>
</html>
```

```typescript
// index.ts
import message from './message'
console.log(message)
```

```typescript
// message.ts
export default 'Hello, world'
```

## Lors de l'utilisation de React

Pour utiliser Typescript + React + JSX, vous avez besoin de :

1. utiliser l'extension `.tsx`
2. importer React correctement
3. utiliser une tsconfig avec une [option spéciale](https://www.typescriptlang.org/docs/handbook/jsx.html) `"jsx": "react"`

Exemple complet :

```html
<!-- index.html -->
<html>
<body>
  <div id="root"></div>
  <script src="./index.tsx"></script>
</body>
</html>
```

```typescript
// index.tsx
import React from 'react'
import ReactDOM from 'react-dom'

console.log('Coucou depuis tsx!')

ReactDOM.render(<p>Coucou</p>, document.getElementById('root'))
```

```json
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react"
  }
}
```

Consultez complétement cette discussion pour plus de détails : https://github.com/parcel-bundler/parcel/issues/1199

---

## File: src/i18n/fr/docs/vue.md

# Vue

_Extensions supportées : `vue`_

---

## File: src/i18n/fr/docs/webAssembly.md

# WebAssembly

_Extensions supportées : `wasm`_

[WebAssembly](https://webassembly.org) est une technologie émergente, mais qui aura un impact énorme sur le Web dans un avenir proche. Maintenant pris en charge par tous les principaux navigateurs web, ainsi que Node, WebAssembly permettra une diversité de langages sur le Web, et pas seulement ceux pouvant transpiler du JavaScript.

Les langages de bas niveau comme le C et Rust peuvent être compilés en WebAssembly, qui est un format binaire pour des fichiers moins volumineux et une exécution plus rapide. Des performances proches de celles du niveau natif peuvent être obtenues avec du code compilé en WebAssembly, souvent beaucoup plus rapide qu'un code JavaScript équivalent. Il est probable que nous verrons des bibliothèques JavaScript qui commenceront à tirer parti de WebAssembly pour les sections critiques d'exécution du code dans un proche avenir.

Parcel le fait **très facilement** pour débuter avec WebAssembly. En supposant que vous avez déjà un fichier `.wasm` (voir la section suivante pour un moyen encore plus facile !), vous pouvez comme d'habitude simplement importer. Les importations synchrones et asynchrones sont prises en charge.

```js
// import synchrone
import { add } from './add.wasm'
console.log(add(2, 3))
// import asynchrone
const { add } = await import('./add.wasm')
console.log(add(2, 3))
```

Lors de l'importation synchrone d'un fichier `.wasm`, Parcel génère automatiquement du code supplémentaire pour précharger le fichier avant l'exécution de votre paquet JavaScript. Cela signifie que le fichier WebAssembly binaire n’est pas inséré dans votre code JavaScript en tant que chaîne, mais qu’il est utilisé comme un fichier binaire distinct comme vous vous en doutiez. De cette manière, votre code fonctionne toujours de manière synchrone, mais Parcel prend en charge le chargement des dépendances pour vous.

Tout cela est possible grâce au support interne de Parcel pour les [chargeurs de paquet](https://github.com/parcel-bundler/parcel/pull/565), qui sont des modules d’exécution qui savent comment charger de manière asynchrone un format de fichier particulier. Dans les versions précédentes, il existait des chargeurs de paquet codés en dur pour JavaScript et CSS, qui permettaient la prise en charge de l'importation dynamique. Dans Parcel v1.5.0, c’est **complètement pluggable**. Vous pouvez définir vos propres chargeurs de paquets dans des plugins ! Cela permettra à l'avenir de nombreuses fonctionnalités intéressantes pour les formats binaires personnalisés tels que les modèles binaires de Glimmer, etc. Super excité de voir ce que cela permet !

---

## File: src/i18n/fr/docs/webManifest.md

# WebManifest

_Extensions supportées : `webmanifest`_

---

## File: src/i18n/fr/docs/yaml.md

# YAML

_Extensions supportées : `yaml`, `yml`_

---

## File: src/i18n/it/docs/api.md

# 📚 API

## Bundler

Invece di utilizzare la CLI, si può anche usare l'API per inizializzare un bundle, per i casi d'uso più avanzati (per esempio l'elaborazione personalizzata dopo ogni build).

Un esempio di "watch" con ogni opzione descritta:

```Javascript
const Bundler = require('parcel-bundler');
const Path = require('path');

// Definizione del file entry-point
const file = Path.join(__dirname, './index.html');

// Opzioni del Bundler
const options = {
  outDir: './dist', // La directory nella quale posizionare l'output del bundle, di default "dist"
  outFile: 'index.html', // Il nome dell' outputFile
  publicUrl: './', // L'url del server, di default "dist"
  watch: true, // Se effettuare o meno il watch dei file, di default la configurazione é process.env.NODE_ENV !== 'production'
  cache: true, // Attiva o disattiva la cache, di default true
  cacheDir: '.cache', // La directory nella quale la cache é salvata, di default é .cache
  minify: false, // Minifica i files, abilitata se process.env.NODE_ENV === 'production'
  target: 'browser', // browser/node/electron, di default é browser
  https: false, // Protocollo del server: https o http, di default é false
  logLevel: 3, // 3 = tutti i log, 2 = log di avvisi & errori, 1 = log degli errori
  hmrPort: 0, // La porta sulla quale gira l'hmr, di default é una porta casuale libera (0 in node.js restituisce una porta casuale libera)
  sourceMaps: true, // Attiva o disattiva le sourcemaps, di default é attivata (non sono ancora supportate nelle build minificate)
  hmrHostname: '', // Un hostname per l'hot module reload, di default é ''
  detailedReport: false // Restituisce un report dettagliato dei bundles, assets, dimensione dei file e timestamps, di default é false, i report vengono generati solo se il watch é disattivato
};

// Inizializza un bundle utilizzando la posizione dell'entry point e le opzioni fornite
const bundler = new Bundler(file, options);

// Esegue il bundle, questo restituisce il bundle principale
// Utilizza gli eventi se stai usando la modalità watch, perché questa promise si eseguirà solo una volta e non per ogni rebuild.
const bundle = await bundler.bundle();
```

### Events

Questo è un elenco di tutti gli eventi del bundler

- `bundled` viene richiamato una volta che Parcel ha terminato con successo il bundling, il [bundle](#bundle) principale viene passato come callback

```Javascript
const bundler = new Bundler(...);
bundler.on('bundled', (bundler) => {
  // contiene tutte le risorse e i bundler, vedi la documentazione ulteriori informazioni
});
```

- `buildEnd` viene chiamato dopo ogni compilazione, restituendo un alert anche se si è verificato un errore

```Javascript
const bundler = new Bundler(...);
bundler.on('buildEnd', () => {
  // Fai qualcosa...
});
```

### Bundle

Un "bundle" è ciò che Parcel usa per raggruppare le risorse, questo contiene anche bundle figli e fratelli per essere in grado di costruire un Albero dei bundle.

#### Proprietà

- `type`: Il tipo di assets che contiene (e.g. js, css, map, ...)
- `name`: Il nome del bundle (generato usando `Asset.generateBundleName()` di `entryAsset`)
- `parentBundle`: Il bundle genitore, é null nel caso non ne abbia
- `entryAsset`: L' entryPoint del bundle, usato per generarne il nome e collezionare gli assets
- `assets`: Un `Set` di tutti gli assets nel bundle
- `childBundles`: Un `Set` di tutti i bundle figli
- `siblingBundles`: Un `Set` di tutti i bundle fratelli
- `siblingBundlesMap`: Un `Map<String(Tipo: js, css, map, ...), Bundle>` di tutti i bundle figli
- `offsets`: Un `Map<Asset, numero(numero di linea nel bundle)>` di tutte le posizioni degli assets nel bundle, usato per generare sourcemaps accurate.

#### Tree

Il `Bundle` contiene un `parentBundle`, `childBunddles` e `siblingBundles`, tutte queste proprietà insieme costituiscono un modo veloce per iterare il Bundle Tree.

Un esempio molto semplice di un Asset Tree e di un Bundle Tree generato:

##### Asset Tree:

`index.html` richiede `index.js` e `index.css`.

`index.js` richiede `test.js` e `test.txt`

```Text
index.html
-- index.js
 |--- test.js
 |--- test.txt
-- index.css
```

##### Bundle Tree:

`index.html` viene usato come asset di entrata per il bundle principale, questo bundle principale crea due bundle figli uno per `index.js` e uno per `index.css` questo perché entrambi sono diversi dal tipo `html`.

`index.js` richiede due files, `test.js` e `test.txt`.

`test.js` viene aggiunto agli assets del bundle `index.js`, in quanto è dello stesso tipo di `index.js``.

`test.txt` crea un nuovo bundle e viene aggiunto come un figlio del bundle `index.js` in quanto è un assetType diverso da `index.js`.

`index.css` non ha requires e quindi contiene solo i suoi assets.

`index.css` e `index.js` sono bundles che sono anche siblingBundles tra di loro, quindi condividono lo stesso genitore.

```Text
index.html
-- index.js (include index.js e test.js)
 |--- test.txt (include test.txt)
-- index.css (include index.css)
```

### Middleware

Middleware può essere usato per agganciarsi a un server http (ad esempio `express` o un nodo `http`).

Un esempio di utilizzo di Parcel middleware con express:

```Javascript
const Bundler = require('parcel-bundler');
const app = require('express')();

// Inizializzare un nuovo bundle usando un file e le opzioni (per le opzioni e il file vedere la documentazione del bundle)
const bundler = new Bundler(file, options);

// Lasciate che express utilizzi il middleware bundler, questo permetterà di gestire ogni richiesta di Parcel sul vostro server express
app.use(bundler.middleware());

// Inizializza il listen sulla porta 8080
app.listen(8080);
```

---

## File: src/i18n/it/docs/asset_types.md

# 📝 Tipi di Asset

Come descritto nella [Documentazione degli Assets](assets.html), Parcel rappresenta ogni file come un `Asset`. I Tipi di Asset sono rappresentati come classi che ereditano da una classe base `Asset` e implementano l'interfaccia richiesta per effettuare il parse, analizzare le dipendenze, convertire, trasformare e generare il codice.

Parcel elabora le risorse in parallelo su più core di elaborazione e le trasformazioni che i tipi di risorse possono eseguire sono limitate a quelle che operano su un singolo file alla volta. Per utilizzare la conversione su più file, è possibile utilizzare un [Packager](packagers.html) personalizzato.

## Interfaccia degli Asset

```javascript
const { Asset } = require('parcel-bundler')

class MyAsset extends Asset {
  type = 'foo' // imposta il tipo principale di output.

  async parse(code) {
    // Parsing del codice su un AST
    return ast
  }

  async pretransform() {
    // facoltativo. converti prima di collezionare le dipendenze.
  }

  collectDependencies() {
    // analizza le dipendenze
    this.addDependency('my-dep')
  }

  async transform() {
    // facoltativo. trasforma dopo aver collezionato le dipendenze.
  }

  async generate() {
    // genera il codice. è possibile effettuare più esecuzioni, se necessario.
    // vengono passati agli appositi packagers per generare i bundle finali.
    return [
      {
        type: 'foo',
        value: 'my stuff here' // output principale
      },
      {
        type: 'js',
        value: 'some javascript', // esecuzione alternativa, da collocare in un bundle JS se necessario
        sourceMap
      }
    ]
  }

  async postProcess(generated) {
    // Processa dopo aver generato tutto il codice
    // Può essere utilizzato per combinare più tipi di Assets
  }
}
```

## Crea un Tipo di Asset

Si può impostare il proprio tipo di Asset con un bundle usando il metodo "addAssetType". Accetta un'estensione di file per la creazione e il percorso del modulo del tipo di Asset. È in forma di percorso, invece che puntare all'oggetto reale, in modo che possa essere passato ai worker process.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addAssetType('.ext', require.resolve('./MioAsset'))
```

---

## File: src/i18n/it/docs/assets.md

# 📦 Assets

Parcel ruota attorno al concetto di Assets. Un Asset può rappresentare qualsiasi file, ma Parcel ha un supporto speciale per alcuni tipi di Assets come i file JavaScript, CSS e HTML. Parcel analizza automaticamente le dipendenze a cui si fa riferimento in questi file e le include nel bundle di output. Gli Assets di tipo simile sono raggruppati nello stesso pacchetto di produzione. Se si importa un asset di tipo diverso (per esempio, se si importa un file CSS da un JS), viene avviato un bundle figlio e viene lasciato un riferimento ad esso nel genitore. Tutto questo processo sarà illustrato nelle sezioni seguenti.

## JavaScript

Il tipo di file più tradizionale per i web bundlers é JavaScript. Parcel supporta sia la sintassi CommonJS che ES6 quando si tratta di importare i files. Supporta anche la funzione di `import()` dinamica per caricare i moduli in modo asincrono, funzionalità che è discussa nella sezione [Code Splitting](code_splitting.html).

```javascript
// Importa un modulo utilizzando la sintassi CommonJS
const dep = require('./percorso/al/file')

// Importa un modulo utilizzando la sintassi ES6
import dep from './percorso/al/file'
```

È anche possibile importare risorse non JavaScript da un file JavaScript, ad esempio CSS o anche un file immagine. Quando si importa uno di questi file, non è incluso come in altri bundle. Invece, è posizionato in un bundle separato (per esempio un file CSS) insieme a tutte le sue dipendenze. Quando si utilizza la tecnica dei [CSS Modules](https://github.com/css-modules/css-modules), le classi esportate vengono posizionate nel bundle JavaScript. Altri tipi di risorse esportano un URL nel file di output nel bundle JavaScript in modo da poterlo consultare nel proprio codice.

```javascript
// Importa un file CSS
import './test.css'

// Importa un file CSS utilizzando CSS Modules
import classNames from './test.css'

// Importa un'immagine da un URL
import imageURL from './test.png'
```

Se si desidera includere un file nel bundle JavaScript al posto di referenziarlo tramite un URL, si può utilizzare l'API di Node.js `fs.readFileSync`. L'URL dovrà essere analizzabile staticamente, cioé non potrà avere nessuna variable al suo interno, (oltre che `__dirname` e `__filename`).

```javascript
import fs from 'fs'

// Legge i contenuti come una stringa
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Legge i contenuti come un Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')
```

## CSS

Gli assets CSS possono essere importati da un file JavaScript o da un file HTML, e possono contenere le dipendenze richiamate dalla sintassi '@import' così come ogni riferimento ad immagini, fonts, eccetera richiamati tramite 'url()'. Gli altri file CSS che sono `@import` saranno inclusi nel medesimo bundle, e i riferimenti agli `url()` saranno riscritti in modo da puntare ai rispettivi files. Tutti i nomi dei file dovrebbero essere richiamati in modo realtivo rispetto al file CSS.

```css
/* Importa un file CSS */
@import './altro.css';

.test {
  /* Riferimento ad un file immagine */
  background: url('./images/background.png');
}
```

Oltre ai semplici CSS, sono supportati e funzionano allo stesso modo anche altri linguaggi compile-to-CSS come LESS, SASS e Stylus.

## SCSS

La compilazione SCSS richiede il modulo `sass`. Per installarlo via npm:

```bash
npm install sass
```

Una volta installato `sass`, puoi importare i file SCSS da un file JavaScript.

```javascript
import './custom.scss'
```

Le dipendenze nel file SCSS possono essere utilizzate tramite la funzione `@import`

## HTML

Le risorse HTML sono spesso il file di input che fornite a Parcel, ma possono anche essere referenziate da file JavaScript, ad esempio per fornire collegamenti ad altre pagine. Gli URL di script, stili, supporti e altri file HTML vengono estratti e compilati come descritto in precedenza. I riferimenti vengono riscritti nell'HTML in modo che si colleghino ai file di output corretti. Tutti i nomi dei file devono essere relativi al file HTML corrente.

```html
<html>
<body>
  <!-- Riferimento ad un file immagine -->
  <img src="./images/header.png">

  <a href="./altrapagina.html">Link ad un'altra pagina</a>

  <!-- Importa un bundle JavaScript -->
  <script src="./index.js"></script>
</body>
</html>
```

---

## File: src/i18n/it/docs/cli.md

# 🖥 CLI

## Comandi

### Serve

Serve inizializza il server di sviluppo, che effettuerà una rebuild della tua app automaticamente ogni volta che cambi qualche file, e supporta l'[hot module replacement](hmr.html) per uno sviluppo più rapido.

```bash
parcel index.html
```

### Build

Build crea gli asset una volta, abilita la minificazione e imposta la variable NODE_ENV per la [Produzione](production.html).

```bash
parcel build index.html
```

### Watch

Il comando watch è simile a serve, con la differenza che non inizializza il server di sviluppo.

```bash
parcel watch index.html
```

### Help

Mostra tutte le possibili opzioni

```bash
parcel help
```

## Opzioni

### Directory di Output

Default: "dist"

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-dir build/output
or
parcel build entry.js -d build/output
```

```base
root
- build
- - output
- - - entry.js
```

### Imposta l'URL pubblico sul quale creare l'app

Default: "/"

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --public-url ./dist/
```

produrrà:

```html
<link rel="stylesheet" type="text/css" href="/dist/entry.1a2b3c.css">
oppure
<script src="/dist/entry.e5f6g7.js"></script>
```

### Target

Default: browser

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --target node
```

Possibili target: node, browser e electron

### Change Log level

Default: 3

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --log-level 1
```

| Loglevel | Effetto             |
| -------- | ------------------- |
| 0        | Logging disattivo   |
| 1        | Log solo errori     |
| 2        | Log errori e avvisi |
| 3        | Log di tutto        |

### HMR Hostname

Default: `location.hostname` della finestra corrente

Disponibile in: `serve`, `watch`

```bash
parcel build entry.js --hmr-hostname parceljs.org
```

### Porta HMR

Default: Una porta casuale libera

Disponibile in: `serve`, `watch`

```bash
parcel build entry.js --hmr-port 8080
```

### Nome del file di Output

Default: Nome del file originale

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-file output.html
```

Questo cambia il nome del file di output del bundle entrypoint

### Produzione di un report dettagliato

Default: Report minimale

Disponibile in: `build`

```bash
parcel build entry.js --detailed-report
```

### Imposta un certificato personalizzato

Default: Genera un certificato

Disponibile in: `serve`

```bash
parcel build entry.js --cert certificate.cert --key private.key
```

### Apri nel browser

Default: apertura disattivata

Disponibile in: `serve`

```bash
parcel build entry.js --open
```

### Disabilita source-maps

Default: source-maps abilitate

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-source-maps
```

### Disabilita autoinstallazione

Default: autoinstallazione abilitata

Disponibile in: `serve`, `watch`

```bash
parcel build entry.js --no-autoinstall
```

### Disabilita HMR

Default: HMR abilitato

Disponibile in: `serve`, `watch`

```bash
parcel build entry.js --no-hmr
```

### Disabilita minificazione

Default: minificazione abilitata

Disponibile in: `build`

```bash
parcel build entry.js --no-minify
```

### Disabilita la cache del filesystem

Default: cache abilitata

Disponibile in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-cache
```

---

## File: src/i18n/it/docs/code_splitting.md

# ✂️ Code Splitting

Parcel supporta il Code Splitting nativamente, senza configurazioni aggiuntive. Ciò consente di dividere il codice dell'applicazione in bundle separati che possono essere caricati su richiesta, il che significa dimensioni iniziali del bundle più piccole e tempi di caricamento più rapidi. Mentre l'utente naviga all'interno dell'applicazione e sono richiesti dei moduli, Parcel si occupa automaticamente di caricare i pacchetti "figli" su richiesta.

Il code splitting é controllato dall'uso della funzione dinamica `import()` [Proposal dynamic import](https://github.com/tc39/proposal-dynamic-import), che funziona come la normale dichiarazione `import` o funzione `require`, ma restituisce una promise. Ciò significa che il modulo viene caricato in modo asincrono.

L'esempio seguente mostra come è possibile utilizzare le importazioni dinamiche per caricare una sotto-pagina dell'applicazione su richiesta.

```javascript
// pagine/about.js
export function render() {
  // Render della pagina
}
```

```javascript
import('./pagine/info').then(function(page) {
  // Render della pagina
  page.render()
})
```

Poiché "import()` restituisce una promise, si può anche usare la sintassi asinc/await. Probabilmente è necessario configurare Babel per convertire la sintassi, fino a quando non sarà più ampiamente supportata dai browser.

```javascript
const page = await import('./pages/about')
// Render della pagina
page.render()
```

Anche le importazioni dinamiche sono gestite in lazy loading in Parcel, così puoi ancora inserire tutte le tue chiamate "import()` nella parte superiore del file e i bundle figli non saranno caricati fino a quando non saranno usati. L'esempio seguente mostra come si possono caricare in modalità lazy loading dinamica le sottopagine di un'applicazione.

```javascript
// Impostare una mappa dei nomi delle pagine per le importazioni dinamiche.
// Questi non vengono caricati fino a quando non vengono utilizzati.
const pages = {
  about: import('./pagine/info'),
  blog: import('./pagine/blog')
}

async function renderPage(name) {
  // Lazy load della pagina richiesta
  const page = await pages[name]
  return page.render()
}
```

**Nota:** Se vuoi usare asinc/await in browser che non lo supportano nativamente, ricorda di includere 'babel-polyfill' nella tua app o 'babel-runtime' + 'babel-plugin-transform-runtime' nelle librerie).

```bash
yarn add babel-polyfill
```

```javascript
import 'babel-polyfill'
import './app'
```

Leggi la documentazione su [babel-polyfill](http://babeljs.io/docs/usage/polyfill) e [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime).

---

## File: src/i18n/it/docs/getting_started.md

# 🚀 Come Iniziare

Parcel è un bundle di applicazioni web, che si differenzia per la sua developer experience (DX). Offre prestazioni incredibili e veloci utilizzando elaborazione multicore e non richiede configurazioni.

Per prima cosa installa Parcel usando Yarn o npm:

Yarn:

```bash
yarn global add parcel-bundler
```

npm:

```bash
npm install -g parcel-bundler
```

Creare un file package.json nella cartella del progetto:

```bash
yarn init -y
```

or

```bash
npm init -y
```

Parcel può prendere qualsiasi tipo di file come entry point, di solito un file HTML o JavaScript è un ottimo punto di partenza. Se si collega un file JavaScript all'HTML usando un percorso relativo, Parcel lo elaborerà e sostituirà il riferimento con un URL al file di output.

Successivamente, creare un file index.html e index.js.

```html
<html>
<body>
  <script src="./index.js"></script>
</body>
</html>
```

```javascript
console.log('hello world')
```

Parcel possiede nativamente un proprio server di sviluppo, che automaticamente ricostruisce la tua app man mano che cambi i file e supporta l'[hot module replacement](hmr.html) per consentire uno sviluppo rapido. Fai puntare il processo semplicemente al tuo entry point:

```bash
parcel index.html
```

Ora apri http://localhost:1234/ nel tuo browser. Puoi anche modificare la porta di default utilizzando l'opzione `-p `.

Usa il server di sviluppo quando non hai un tuo server, o la tua applicazione è interamente resa lato client. Se si dispone di un proprio server, è possibile eseguire Parcel in modalità "watch". Questa modalità traccia automaticamente il cambiamento dei file e supporta l'hot module replacement, ma non avvia un web server.

```bash
parcel watch index.html
```

Quando sei soddisfatto puoi creare una build di Produzione. Questa modalità disattiva il "watch" ed effettua una build soltanto. Vedi la sezione [Produzione](production.html) per ulteriori informazioni.

---

## File: src/i18n/it/docs/hmr.md

# 🔥 Hot Module Replacement

Hot Module Replacement (HMR) migliora l'esperienza di sviluppo aggiornando automaticamente i moduli nel browser durante l'esecuzione senza bisogno di un intero aggiornamento della pagina. Questo significa che lo stato dell'applicazione può essere mantenuto quando si implementano piccoli cambiamenti nel codice. L'implementazione HMR di Parcel supporta sia JavaScript che CSS. L'HMR viene disattivato automaticamente quando si esegue il bundle in modalità di produzione.

Quando si salvano i file, Parcel ricostruisce ciò che è cambiato e invia un aggiornamento a tutti i client in esecuzione contenenti il nuovo codice. Il nuovo codice sostituisce la vecchia versione e viene rivalutato insieme a tutti i genitori. Potete agganciarvi a questo processo usando l'API `module.hot`, che può notificare il vostro codice quando un modulo sta per essere scartato, o quando arriva una nuova versione. Progetti come [react-hot-loader](https://github.com/gaearon/react-hot-loader) possono essere d'aiuto in questo processo, e funzionano da subito con Parcel.

Ci sono due metodi da conoscere: `module.hot.accept` e `module.hot.dispose`. Si invoca `module.hot.accept` con una funzione di richiamo che viene eseguita quando il modulo o una delle sue dipendenze vengono aggiornati. Il `module.hot.dispose` accetta una callback che viene chiamata quando il modulo sta per essere sostituito.

```javascript
if (module.hot) {
  module.hot.dispose(function() {
    // il modulo sta per essere sostituito
  })

  module.hot.accept(function() {
    // il modulo o una delle sue dipendenze è stato appena aggiornato
  })
}
```

## Safe Write

Alcuni editor di testo e IDE hanno una funzione chiamata "safe write" che previene la perdita di dati, prendendo una copia del file e rinominandola una volta salvata.

Quando si utilizza Hot Module Reload (HMR) questa funzione blocca il rilevamento automatico degli aggiornamenti dei file, per disabilitare il "safe write" utilizzare le opzioni fornite di seguito:

- `Sublime Text 3` aggiungere atomic_save: "false" alle tue impostazioni utente.
- `IntelliJ` usa la ricerca nelle impostazioni per trovare "safe write" e disabilitarlo.
- `Vim` aggiungere :set backupcopy=yes alle tue impostazioni utente.
- `WebStorm` disattiva Usa "safe write" in Preferences > Appearance & Behavior > System Settings.

---

## File: src/i18n/it/docs/how_it_works.md

# 🛠 Come Funziona

Parcel trasforma un tree di **assets** in un tree di **bundles**. Molti altri bundler sono fondamentalmente basati su risorse JavaScript, con altri formati affrontati - ad esempio alternate come stringhe in file JS. Parcel è agnostico di tipo file: funziona con qualsiasi tipo di assets nel modo che ci si aspetterebbe, senza alcuna configurazione necessaria. Il processo di bundling di Parcel si articola in tre fasi.

### 1. Costruzione dell'Asset Tree

Il pacchetto prende come input un singolo asset, che può essere di qualsiasi tipo: un file JS, HTML, CSS, immagine, ecc. Ci sono vari [Tipi di Assets](asset_types.html) definiti in Parcel che sanno come gestire specifici tipi di file. Gli asset sono analizzati, le loro dipendenze sono estratte e trasformate nel rispettivo modulo compilabile finale. In questo modo si crea una struttura ad albero degli assets.

### 2. Costruzione del Bundle Tree

Una volta che l'Asset Tree è stato costruito, gli asset sono inseriti in un Bundle Tree. Un bundle viene creato per l'entry asset, e i bundle figli sono creati per "import()` dinamici, per permettere il Code Splitting.

I bundle fratelli vengono creati quando vengono importate risorse di tipo diverso, per esempio se si importa un file CSS da JavaScript, questo viene inserito in un bundle fratello nel corrispondente JavaScript.

Se una risorsa è richiesta in più di un bundle, viene spostata fino all'antenato comune (nodo) più vicino nell'albero dei Bundle, pertanto non viene inclusa più di una volta.

### 3. Packaging

Dopo che un Bundle Tree viene costruito, ogni bundle viene scritto in un file da un [packager](packagers.html) specifico per quel tipo di file. I Packagers sanno come compilare il codice di ogni asset insieme nel file di output finale che verrà creato e caricato dal browser.

---

## File: src/i18n/it/docs/meta.json

{
  "*": {
    "language": "it"
  }
}

---

## File: src/i18n/it/docs/packagers.md

# 📦 Packagers

In Parcel, un `Packager` combina multipli `Assets` insieme in un bundle di output finale. Questo succede nel processo principale dopo che tutti gli asset sono stati processati, e un Albero dei Bundle é stato creato. I Packagers sono registrati sulla base del tipo di file, e gli assets che hanno generato quel tipo di output sono inviati al packagers per la creazione del file finale di output.

## Interfaccia del Packager

```javascript
const { Packager } = require('parcel-bundler')

class MioPackager extends Packager {
  async start() {
    // facoltativo. scrive il file header se richiesto.
    await this.dest.write(header)
  }

  async addAsset(asset) {
    // obbligatorio. scrive l'asset nel file output
    await this.dest.write(asset.generated.foo)
  }

  async end() {
    // facoltativo. scrive il file trailer se richiesto.
    await this.dest.end(trailer)
  }
}
```

## Impostare un Packager

Puoi impostare il tuo packager con un bundler usando il metodo `addPackager`. Accetta un tipo di file da impostare, e il percorso al tuo modulo packager.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addPackager('foo', require.resolve('./MioPackager'))
```

---

## File: src/i18n/it/docs/plugins.md

# 🔌 Plugins

Parcel adotta un approccio leggermente diverso da molti altri strumenti, in quanto molti formati comuni sono inclusi già pronti senza la necessità di installare e configurare plugin aggiuntivi. Tuttavia, ci sono casi in cui si potrebbe voler estendere Parcel in modo non standard, e in questo caso si può ricorrere ai plugins. I plugin installati vengono rilevati e caricati automaticamente in base alle dipendenze di `package.json`.

Quando si aggiunge il supporto per un nuovo formato di file a Parcel, si dovrebbe prima considerare quanto sia diffuso e quanto ne sia standardizzata l'implementazione. Se è sufficientemente diffuso e standard, il formato dovrebbe probabilmente essere aggiunto al core di Parcel piuttosto che come plugin che gli utenti possano installare. In caso di dubbi, [GitHub](https://github.com/parcel-bundler/parcel/issues) è il posto giusto per discuterne.

## Plugin API

I plugin per Parcel sono molto semplici. Sono semplicemente moduli che esportano una singola funzione, che viene richiamata automaticamente da Parcel durante l'inizializzazione. La funzione riceve come input l'oggetto `Bundler` e può fare configurazioni come l'impostazione o l'aggiunta dei tipi di asset e dei Packagers.

```javascript
module.exports = function(bundler) {
  bundler.addAssetType('ext', require.resolve('./MioAsset'))
  bundler.addPackager('foo', require.resolve('./MioPackager'))
}
```

Puoi pubblicare questo pacchetto su npm usando il prefisso `parcel-plugin-``, e sarà automaticamente rilevato e caricato come descritto di seguito.

## Utilizzare i Plugins

Utilizzare i plugin in Parcel non potrebbe essere più semplice. Tutto quello che dovete fare è installarli e salvarli nel vostro `package.json`. I plugin dovrebbero essere nominati con il prefisso `parcel-plugin-`, ad esempio `parcel-plugin-foo`. Tutte le dipendenze elencate in `package.json` con questo prefisso verranno caricate automaticamente durante l'inizializzazione.

---

## File: src/i18n/it/docs/production.md

# ✨ Produzione

Quando si tratta di preparare l'applicazione per il server di Produzione, è possibile utilizzare la modalità di Produzione di Parcel.

```bash
parcel build entry.js
```

disabilita la modalità watch e l'hot module replacement in modo che si possa creare una sola volta la build. Consente inoltre di minificare tutti i bundle di output di ridurre le dimensioni del file. I minificatori utilizzati da Parcel sono [terser](https://github.com/fabiosantoscode/terser) per JavaScript, [cssnano](http://cssnano.co) per CSS e [htmlnano](https://github.com/posthtml/htmlnano) per HTML.

L'abilitazione della modalità di Produzione imposta anche la variabile d'ambiente `NODE_ENV=production`. Le grandi librerie come React hanno solo funzioni di debug per lo sviluppo che sono disabilitate impostando questa variabile d'ambiente, il che si traduce in build più piccoli e veloci per la Produzione.

---

## File: src/i18n/it/docs/recipes.md

# 🍰 Ricette

## React

Come prima cosa installa le dipendenze di React

[Vedi Post](http://blog.jakoblind.no/react-parcel/)

```bash
npm install --save react
npm install --save react-dom
npm install --save-dev parcel-bundler
```

<sub>Oppure, se si vuole utilizzare Yarn</sub>

```bash
yarn add react
yarn add react-dom
yarn add --dev parcel-bundler
```

Aggiungi uno script di Start nel `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Preact

Come prima cosa installa le dipendenze di Preact

```bash
npm install --save preact
npm install --save preact-compat
npm install --save-dev parcel-bundler
npm install --save-dev babel-preset-env
npm install --save-dev babel-preset-preact
```

<sub>Oppure, se si vuole utilizzare Yarn</sub>

```bash
yarn add preact
yarn add preact-compat
yarn add --dev parcel-bundler
yarn add --dev babel-preset-env
yarn add --dev babel-preset-preact
```

Poi assicurati che questa configurazione di Babel sia presente.

```javascript
// .babelrc
{
  "presets": ["env", "preact"]
}
```

Aggiungi uno script di Start nel `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

## Vue

Come prima cosa installa le dipendenze di Vue

```bash
npm install --save vue
npm install --save-dev parcel-bundler
```

<sub>Oppure, se si vuole utilizzare Yarn</sub>

```bash
yarn add vue
yarn add --dev parcel-bundler
```

Aggiungi uno script di Start nel `package.json`

```javascript
// package.json
"scripts": {
  "start": "parcel index.html"
}
```

---

## File: src/i18n/it/docs/transforms.md

# 🐠 Conversioni

Mentre molti bundlers richiedono l'installazione di plugins per convertire o processare i tuoi asset, Parcel supporta nativamente molti preprocessori e transpilers. Puoi processare JavaScript usando [Babel](https://babeljs.io), CSS usando [PostCSS](http://postcss.org), and HTML usando [PostHTML](https://github.com/posthtml/posthtml). Parcel attiverà automaticamente queste conversioni se troverà un file di configurazione (es. `.babelrc`, `.postcssrc`) in un modulo.

Questo processo funziona anche in `node_modules` di terze parti: se un file di configurazione viene pubblicato come parte del bundle, la conversione viene attivata automaticamente solo per quel modulo. In questo modo il processo di bundling continua ad essere veloce, poiché vengono elaborati solo i moduli che devono essere convertiti. Significa anche che non è necessario configurare manualmente le conversioni per includere ed escludere determinati file, o conoscere come codice di terze parti è stato costruito al fine di usarlo nella propria applicazione.

## Babel

[Babel](https://babeljs.io) è un famoso transpiler per JavaScript, con un grosso ecosistema di plugins. Usare Babel con Parcel funziona esattamente come se si stesse usando da solo o con altri bundlers.

Installa i preset e i plugins nella tua app:

```bash
yarn add @babel/preset-env
```

Poi, crea un file `.babelrc`:

```json
{
  "presets": ["@babel/preset-env"]
}
```

## PostCSS

[PostCSS](http://postcss.org) é un tool per convertire il CSS con dei plugins, come [autoprefixer](https://github.com/postcss/autoprefixer), [Preset Env](https://github.com/csstools/postcss-preset-env), e [CSS Modules](https://github.com/css-modules/css-modules). Puoi configurare PostCSS con Parcel creando un file di configurazione con uno di questi nomi: `.postcssrc` (JSON), `.postcssrc.js`, o `postcss.config.js`.

Installa i plugins nella tua app:

```bash
yarn add postcss-modules autoprefixer
```

Poi, crea un file `.postcssrc`:

```json
{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}
```

I plugin sono specificati nell'oggetto "plugin" come chiavi e le opzioni sono definite utilizzando i valori dell'oggetto. Se non ci sono opzioni per un plugin, basta impostarlo su "true".

I browser di destinazione per Autoprefixer, cssnext e altri strumenti possono essere specificati nel file `.browserslistrc`:

```
> 1%
last 2 versions
```

I moduli CSS sono abilitati in modo leggermente diverso usando la chiave top level `modules`. Questo perché Parcel ha bisogno di avere un supporto speciale per i CSS Modules, dato che questo tool esporta un oggetto da includere nel bundle JavaScript. Si noti che è ancora necessario installare "postcss-modules" nel progetto.

### Utilizzo con librerie CSS esistenti

Affinché i CSS Modules funzionino correttamente con i file esistenti, è necessario specificare questo supporto nel proprio `.postcssrc`.

## PostHTML

[PostHTML](https://github.com/posthtml/posthtml) è un tool per convertire i file HTML con dei plugins. Puoi configurare PostHTML con Parcel creando un file di configurazione con questi nomi: `.posthtmlrc` (JSON), `.posthtmlrc.js`, o `posthtml.config.js`.

Installa i plugins nella tua app:

```bash
yarn add posthtml-img-autosize
```

Poi, crea un file `.posthtmlrc`:

```json
{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}
```

I Plugins sono specificati nell'oggetto `plugins` come chiavi, e le opzioni sono definite utilizzando i valori dell'oggetto. Se non ci sono opzioni per un plugin, settatelo semplicemente `true`.

## TypeScript

[TypeScript](https://www.typescriptlang.org/) è un superset di JavaScript che si compila in Javascript classico che supporta anche le feature delle versioni ES2015+. La Conversione di TypeScript funziona nativamente senza necessirà di configurazioni aggiuntive.

```html
<!-- index.html -->
<html>
  <body>
    <script src="./index.ts"></script>
  </body>
</html>
```

```typescript
// index.ts
import message from './message'
console.log(message)
```

```typescript
// message.ts
export default 'Ciao, Mondo'
```

## ReasonML/BuckleScript

[ReasonML](https://reasonml.github.io/) compila OCaml in JavaScript con l'aiuto di [BuckleScript](https://bucklescript.github.io). Puoi utilizzare ReasonML installando le sue dipendenze e creando un file `bsconfig.json`:

```bash
$ yarn add bs-platform --dev
```

```json
// bsconfig.json
// da https://github.com/BuckleScript/bucklescript/blob/master/jscomp/bsb/templates/basic-reason/bsconfig.json

{
  "name": "blabla",
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```html
<!-- index.html -->
<html>
  <body>
    <script src="./src/index.re"></script>
  </body>
</html>
```

```reason
/* src/index.re */
print_endline("Ciao Mondo");
```

### ReasonReact

[ReasonReact](https://reasonml.github.io/reason-react/) é un Binding di React per ReasonML. Puoi utilizzarlo anche con Parcel:

```bash
$ yarn add react react-dom reason-react
```

```html
<!-- index.html -->
<html>
  <body>
    <script src="./src/index.re"></script>
  </body>
</html>
```

```diff
// bsconfig.json

{
  "name": "blabla",
+ "reason": {
+   "react-jsx": 2
+ },
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [
+   "reason-react"
  ],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```html
<!-- index.html -->
<html>
  <body>
    <div id="app"></div>
    <script src="./src/index.re"></script>
  </body>
</html>
```

```reason
/* src/Greeting.re */

let component = ReasonReact.statelessComponent("Saluta");

let make = (~name, _children) => {
  ...component,
  render: _self =>
    <div>
      {ReasonReact.stringToElement("Ciao! " ++ name)}
    </div>
};
```

```reason
/* src/index.re */

ReactDOMRe.renderToElementWithId(<Saluta name="Parcel" />, "app");
```

---

## File: src/i18n/ja/docs/api.md

# 📚 API

## Bundler

Instead of the CLI you can also use the API to initialise a bundler, for more advanced use-cases (e.g. custom processing after every build).
A watch example with every option explained:

```Javascript
const Bundler = require('parcel-bundler');
const Path = require('path');

// Single entrypoint file location:
const entryFiles = Path.join(__dirname, './index.html');
// OR: Multiple files with globbing (can also be .js)
// const entryFiles = './src/*.js';
// OR: Multiple files in an array
// const entryFiles = ['./src/index.html', './some/other/directory/scripts.js'];

// Bundler options
const options = {
  outDir: './dist', // The out directory to put the build files in, defaults to dist
  outFile: 'index.html', // The name of the outputFile
  publicUrl: './', // The url to serve on, defaults to dist
  watch: true, // Whether to watch the files and rebuild them on change, defaults to process.env.NODE_ENV !== 'production'
  cache: true, // Enabled or disables caching, defaults to true
  cacheDir: '.cache', // The directory cache gets put in, defaults to .cache
  contentHash: false, // Disable content hash from being included on the filename
  global: 'moduleName', // Expose modules as UMD under this name, disabled by default
  minify: false, // Minify files, enabled if process.env.NODE_ENV === 'production'
  scopeHoist: false, // Turn on experimental scope hoisting/tree shaking flag, for smaller production bundles
  target: 'browser', // Browser/node/electron, defaults to browser
  bundleNodeModules: false, // By default, package.json dependencies are not included when using 'node' or 'electron' with 'target' option above. Set to true to adds them to the bundle, false by default
  https: { // Define a custom {key, cert} pair, use true to generate one or false to use http
    cert: './ssl/c.crt', // Path to custom certificate
    key: './ssl/k.key' // Path to custom key
  },
  logLevel: 3, // 5 = save everything to a file, 4 = like 3, but with timestamps and additionally log http requests to dev server, 3 = log info, warnings & errors, 2 = log warnings & errors, 1 = log errors
  hmr: true, // Enable or disable HMR while watching
  hmrPort: 0, // The port the HMR socket runs on, defaults to a random free port (0 in node.js resolves to a random free port)
  sourceMaps: true, // Enable or disable sourcemaps, defaults to enabled (minified builds currently always create sourcemaps)
  hmrHostname: '', // A hostname for hot module reload, default to ''
  detailedReport: false // Prints a detailed report of the bundles, assets, filesizes and times, defaults to false, reports are only printed if watch is disabled
};

(async function() {
  // Initializes a bundler using the entrypoint location and options provided
  const bundler = new Bundler(entryFiles, options);

  // Run the bundler, this returns the main bundle
  // Use the events if you're using watch mode as this promise will only trigger once and not for every rebuild
  const bundle = await bundler.bundle();
})();
```

If you want to use/start the built-in development server of Parcel you can use `bundler.serve()`. This calls `bundler.bundle()` and starts a simple http (or https) server. `serve()` takes in 3 arguments (they are all optional), first one is port, second one is https (this can either be an object `{cert,key}` pointing to the location of key and cert file or `true` to generate a key) and the third one is the host.

### Events

This is a list of all bundler events

- `bundled` gets called once Parcel has successfully finished bundling **for the first time**, the main [bundle](#bundle) instance gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('bundled', (bundle) => {
  // bundler contains all assets and bundles, see documentation for details
});
// Call this to start bundling
bundler.bundle();
```

- `buildEnd` gets called after each build (aka **including every rebuild**), this also emits if an error occurred

```Javascript
const bundler = new Bundler(...);
bundler.on('buildEnd', () => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

- `buildStart` gets called at the start of the first build, the `entryFiles` Array gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('buildStart', entryPoints => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

- `buildError` gets called every time an error occurs during builds, the `Error` Object gets passed to the callback

```Javascript
const bundler = new Bundler(...);
bundler.on('buildError', error => {
  // Do something...
});
// Call this to start bundling
bundler.bundle();
```

### Bundle

A `Bundle` is what Parcel uses to bundle assets together, this also contains child and sibling bundles to be able to build a bundle tree.

#### Properties

- `type`: The type of assets it contains (e.g. js, css, map, ...)
- `name`: The name of the bundle (generated using `Asset.generateBundleName()` of `entryAsset`)
- `parentBundle`: The parent bundle, is null in case of the entry bundle
- `entryAsset`: The entryPoint of the bundle, used for generating the name and gathering assets.
- `assets`: A `Set` of all assets inside the bundle
- `childBundles`: A `Set` of all child bundles
- `siblingBundles`: A `Set` of all sibling bundles
- `siblingBundlesMap`: A `Map<String(Type: js, css, map, ...), Bundle>` of all sibling bundles
- `offsets`: A `Map<Asset, number(line number inside the bundle)>` of all the locations of the assets inside the bundle, used to generate accurate source maps

#### Tree

The `Bundle` contains a `parentBundle`, `childBundles` and `siblingBundles`, all these properties together create a fast to iterate bundle tree.

A very basic example of an asset tree and it's generated bundle Tree

##### Asset tree:

`index.html` requires `index.js` and `index.css`.

`index.js` requires `test.js` and `test.txt`

```Text
index.html
-- index.js
 |--- test.js
 |--- test.txt
-- index.css
```

##### Bundle Tree:

`index.html` gets used as an entry asset for the main bundle, this main bundle creates two child bundles one for `index.js` and one for `index.css` this because they both are different from the `html` type.

`index.js` requires two files, `test.js` and `test.txt`.

`test.js` gets added to the assets of the `index.js` bundle, as it is of the same type as `index.js`

`test.txt` creates a new bundle and gets added as a child of the `index.js` bundle as it is a different assetType than `index.js`

`index.css` has no requires and therefore only contains it's entry Asset.

`index.css` and `index.js` bundles are siblingBundles of each other as they share the same parent.

```Text
index.html
-- index.js (includes index.js and test.js)
 |--- test.txt (includes test.txt)
-- index.css (includes index.css)
```

### Middleware

Middleware can be used to hook into an http server (e.g. `express` or node `http`).

An example of using the Parcel middleware with express

```Javascript
const Bundler = require('parcel-bundler');
const app = require('express')();

const file = 'index.html'; // Pass an absolute path to the entrypoint here
const options = {}; // See options section of api docs, for the possibilities

// Initialize a new bundler using a file and options
const bundler = new Bundler(file, options);

// Let express use the bundler middleware, this will let Parcel handle every request over your express server
app.use(bundler.middleware());

// Listen on port 8080
app.listen(8080);
```

---

## File: src/i18n/ja/docs/asset_types.md

# 📝 Asset Types

As described in the [Assets documentation](assets.html), Parcel represents each input file as an `Asset`. Asset types are represented as classes inheriting from the base `Asset` class and implementing the required interface to parse, analyze dependencies, transform, and code generate.

Because Parcel processes assets in parallel across multiple processor cores, the transforms that asset types can perform are limited to those that operate on a single file at a time. For transforms across multiple files, a custom [Packager](packagers.html) can be used.

## Asset Interface

```javascript
const { Asset } = require('parcel-bundler')

class MyAsset extends Asset {
  type = 'foo' // set the main output type.

  async parse(code) {
    // parse code to an AST
    return ast
  }

  async pretransform() {
    // optional. transform prior to collecting dependencies.
  }

  collectDependencies() {
    // analyze dependencies
    this.addDependency('my-dep')
  }

  async transform() {
    // optional. transform after collecting dependencies.
  }

  async generate() {
    // code generate. you can return multiple renditions if needed.
    // results are passed to the appropriate packagers to generate final bundles.
    return [
      {
        type: 'foo',
        value: 'my stuff here' // main output
      },
      {
        type: 'js',
        value: 'some javascript', // alternative rendition to be placed in JS bundle if needed
        sourceMap
      }
    ]
  }

  async postProcess(generated) {
    // Process after all code generating has been done
    // Can be used for combining multiple asset types
  }
}

module.exports = MyAsset
```

## Registering an Asset Type

You can register your asset type with a bundler using the `addAssetType` method. It accepts a file extension to register, and the path to your asset type module. It is a path rather than the actual object so that it can be passed to worker processes.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addAssetType('.ext', require.resolve('./MyAsset'))
```

---

## File: src/i18n/ja/docs/assets.md

# 📦 Assets

Parcel はアセットに基づいています。アセットは様々なファイルのことを表しますが、JavaScript、CSS、HTML など特定の種類のアセットについては特別なサポートがあります。Parcel はこれらのファイルから、参照されている依存を自動で解析して出力するバンドルに含めます。同じような種類のアセットはグループ化され、同じバンドルにまとめられます。異なる種類のアセットをインポートすると（例: CSS ファイルを JS ファイルからインポートした場合）、子バンドルが作成され、親バンドルへの参照が残されます。これについては、別のセクションで説明します。

もしドキュメントに特定の種類のアセットが見つからない場合は、ドキュメントが古い可能性があります。サポートされているアセットの種類のリストは[parcel/src/Parser.js](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/Parser.js#L10)で確認できます。
パーサーのリストは[parcel/src/assets/](https://github.com/parcel-bundler/parcel/tree/master/packages/core/parcel-bundler/src/assets)で確認できます。

デフォルトでサポートされていない種類のアセットについては、以下のリンクからサポートするプラグインがあるか探すことができます。

- [Yarn](https://yarnpkg.com/en/packages?q=parcel-plugin-&p=1)
- [npm](https://www.npmjs.com/search?q=parcel-plugin-)
- [awesome-parcel](https://github.com/parcel-bundler/awesome-parcel#plugins)

または [自分でプラグインを作ることもできます](https://parceljs.org/plugins.html)。

---

## File: src/i18n/ja/docs/cli.md

# 🖥 CLI

## Commands

### Serve

Starts up a development server, which will automatically rebuild your app as you change files and supports [hot module replacement](hmr.html) for fast development.

```bash
parcel index.html
```

### Build

Builds the assets once, it also enabled minification and sets the `NODE_ENV=production` environment variable. See [Production](production.html) for more details.

```bash
parcel build index.html
```

### Watch

The `watch` command is similar to `serve`, with the main difference being it doesn't start up a server.

```bash
parcel watch index.html
```

### Help

Displays all possible cli options

```bash
parcel help
```

### Version

Displays Parcel version number

```bash
parcel --version
```

## Options

### Output directory

Default: "dist"

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-dir build/output
# or
parcel build entry.js -d build/output
```

```base
root
- build
- - output
- - - entry.js
```

### Set the public URL to serve on

Default: "/"

Available in: `serve`, `watch`, `build`

```bash
parcel entry.js --public-url ./dist/
```

will output:

```html
<link rel="stylesheet" type="text/css" href="dist/entry.1a2b3c.css" />
<!-- or -->
<script src="dist/entry.e5f6g7.js"></script>
```

### Target

Default: browser

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --target node
```

⚠️ Target `node` and `electron` will not bundle package.json's `dependencies` (but will include `devDependencies`). This behavior can be overriden using [--bundle-node-modules](#force-node-modules-bundling) flag (see below).

Possible targets: `node`, `browser`, `electron`

### Force node modules bundling

Default: false

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --target node --bundle-node-modules
```

By default, package.json's `dependencies` are not included when using `--target node` or `--target electron`. This flag adds them to the bundle.

### Cache directory

Default: ".cache"

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --cache-dir build/cache
```

### Port

Default: 1234

Available in: `serve`

```bash
parcel serve entry.js --port 1111
```

### Change Log level

Default: 3

Available in: `serve`, `watch`, `build`

```bash
parcel entry.js --log-level 1
```

| Loglevel | Effect                                                                                          |
| -------- | ----------------------------------------------------------------------------------------------- |
| 0        | Logging disabled                                                                                |
| 1        | Only log errors                                                                                 |
| 2        | Log errors and warnings                                                                         |
| 3        | Log errors, warnings and info                                                                   |
| 4        | Verbose (keep everything in log with timestamps  and also log http requests to dev server) |
| 5        | Debug (save everything to a file with timestamps)                                               |

### HMR Hostname

Default: `location.hostname` of current window

Available in: `serve`, `watch`

```bash
parcel entry.js --hmr-hostname parceljs.org
```

### HMR Port

Default: A random available port

Available in: `serve`, `watch`

```bash
parcel entry.js --hmr-port 8080
```

### Output filename

Default: Original filename

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --out-file output.html
```

This changes the output filename of the entrypoint bundle

### Print a detailed report

Default: Minimal report

Available in: `build`

```bash
parcel build entry.js --detailed-report
```

### Enable https

Default: https disabled

Available in: `serve`, `watch` (listen on HTTPS for HMR connections)

```bash
parcel build entry.js --https
```

⚠️ This flag generates a self-signed certificate, you might have to configure your browser to allow self-signed certificates for localhost.

### Set a custom certificate

Default: https disabled

Available in: `serve`, `watch`

```bash
parcel entry.js --cert certificate.cert --key private.key
```

### Open in browser

Default: open disabled

Available in: `serve`

```bash
parcel entry.js --open
```

### Disable source-maps

Default: source-maps enabled

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-source-maps
```

### Disable autoinstall

Default: autoinstall enabled

Available in: `serve`, `watch`

```bash
parcel entry.js --no-autoinstall
```

### Disable HMR

Default: HMR enabled

Available in: `serve`, `watch`

```bash
parcel entry.js --no-hmr
```

### Disable minification

Default: minification enabled

Available in: `build`

```bash
parcel build entry.js --no-minify
```

### Disable the filesystem cache

Default: cache enabled

Available in: `serve`, `watch`, `build`

```bash
parcel build entry.js --no-cache
```

### Expose modules as UMD

Default: disabled

Available in: `serve`, `watch`, `build`

```bash
parcel serve entry.js --global myvariable
```

### Enable experimental scope hoisting/tree shaking support

Default: disabled

Available in: `build`

```bash
parcel build entry.js --experimental-scope-hoisting
```

For more information, see the [Tree Shaking section](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) of Devon Govett's post on Parcel 1.9.

---

## File: src/i18n/ja/docs/code_splitting.md

# ✂️ Code Splitting

Parcel supports zero configuration code splitting out of the box. This allows you to split your application code into separate bundles which can be loaded on demand, which means smaller initial bundle sizes and faster load times. As the user navigates around in your application and modules are required, Parcel automatically takes care of loading child bundles on demand.

Code splitting is controlled by use of the dynamic `import()` function [syntax proposal](https://github.com/tc39/proposal-dynamic-import), which works like the normal `import` statement or `require` function, but returns a Promise. This means that the module is loaded asynchronously.

## Using dynamic imports

The following example shows how you might use dynamic imports to load a sub-page of your application on demand.

```javascript
// pages/about.js
export function render() {
  // Render the page
}
```

```javascript
import('./pages/about').then(function(page) {
  // Render page
  page.render()
})
```

## Dynamic imports with async/await

Because `import()` returns a Promise, you can also use async/await syntax. You probably need to configure Babel to transpile the syntax though, until it is more widely supported by browsers.

```javascript
const page = await import('./pages/about')
// Render page
page.render()
```

Dynamic imports are also lazily loaded in Parcel, so you can still put all your `import()` calls at the top of your file and the child bundles won't be loaded until they are used. The following example shows how you might lazily load sub-pages of an application dynamically.

```javascript
// Setup a map of page names to dynamic imports.
// These are not loaded until they are used.
const pages = {
  about: import('./pages/about'),
  blog: import('./pages/blog')
}

async function renderPage(name) {
  // Lazily load the requested page.
  const page = await pages[name]
  return page.render()
}
```

**Note:** If you would like to use async/await in browsers that don't support it natively, remember to include `babel-polyfill` in your app or `babel-runtime` + `babel-plugin-transform-runtime` in libraries.

```bash
yarn add babel-polyfill
```

```javascript
import 'babel-polyfill'
import './app'
```

Read the docs on [babel-polyfill](http://babeljs.io/docs/usage/polyfill) and [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime).

## Bundle resolution

Parcel infers the location of bundles automatically. This is done in the [bundle-url](https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/builtins/bundle-url.js) module, and uses the stack trace to determine the path where the initial bundle was loaded.

This means you don't need to configure where bundles should be loaded from, but also means you must serve the bundles from the same location.

Parcel currently resolves bundles at the following protocols: `http`, `https`, `file`, `ftp`, `chrome-extension` and `moz-extension`.

---

## File: src/i18n/ja/docs/coffeeScript.md

# CoffeeScript

_Supported extensions: `coffee`_

[CoffeeScript](https://coffeescript.org) is a language that transpiles to JavaScript, which allows you to use a shorter syntax and other features like [the existential operator](https://coffeescript.org/#existential-operator), [shorter array-splicing syntax](https://coffeescript.org/#slices), [block regular expressions](https://coffeescript.org/#regexes) and more.

```coffeescript
# log.coffee
console.log 'Hello there!'
```

```javascript
// index.js
import './log'
```

---

## File: src/i18n/ja/docs/css.md

# CSS

_Supported extensions: `css`, `pcss`, `postcss`_

CSS assets can be imported from a JavaScript or HTML file:

```js
import './index.css'
```

```html
<link rel="stylesheet" type="text/css" href="index.css" />
```

CSS assets can contain dependencies referenced by `@import` syntax as well as references to images, fonts, etc. via the `url()` function. Other CSS files that are `@import`ed are inlined into the same CSS bundle, and `url()` references are rewritten to their output filenames. All filenames should be relative to the current CSS file.

```css
/* Import another CSS file */
@import './other.css';

.test {
  /* Reference an image file */
  background: url('./images/background.png');
}
```

In addition to plain CSS, other compile-to-CSS languages like LESS, SASS, and Stylus are also supported, and work the same way.

# PostCSS

[PostCSS](http://postcss.org) is a tool for transforming CSS with plugins, like [autoprefixer](https://github.com/postcss/autoprefixer), [Preset Env](https://github.com/csstools/postcss-preset-env), and [CSS Modules](https://github.com/css-modules/css-modules). You can configure PostCSS with Parcel by creating a configuration file using one of these names: `.postcssrc` (JSON), `.postcssrc.js`, or `postcss.config.js`.

Install plugins in your app:

```bash
yarn add postcss-modules autoprefixer
```

Then, create a `.postcssrc`:

```json
{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}
```

Plugins are specified in the `plugins` object as keys, and options are defined using object values. If there are no options for a plugin, just set it to `true` instead.

Target browsers for Autoprefixer, cssnext and other tools can be specified in `.browserslistrc` file:

```
> 1%
last 2 versions
```

CSS Modules are enabled slightly differently using the a top-level `modules` key. This is because Parcel needs to have special support for CSS Modules since they export an object to be included in the JavaScript bundle as well. Note that you still need to install `postcss-modules` in your project.

## Usage with existing CSS libraries

For CSS Modules to work properly with existing modules they need to specify this support in their own `.postcssrc`.

## Set cssnano minify config

Parcel adds [cssnano](http://cssnano.co) to postcss in order to minify css in production build, where custom configuration can be set by creating `cssnano.config.js` file:

```js
module.exports = {
  preset: [
    'default',
    {
      calc: false,
      discardComments: {
        removeAll: true
      }
    }
  ]
}
```

---

## File: src/i18n/ja/docs/elm.md

# Elm

_Supported extensions: `elm`_

[Elm](https://elm-lang.org/) is a functional language with an advanced type
system that ensures correctnes of your code and prevents confusing runtime
errors. With its focus on simplicity and speed, Elm is a great choice when it
comes to building webapps of all kinds. Parcel supports Elm right out of the box
without the need for any additional configuration.

```html
<!-- index.html -->

<html>
  <body>
    <main></main>
    <script src="./index.js"></script>
  </body>
</html>
```

```javascript
// index.js

import { Elm } from './Main.elm'

Elm.Main.init({
  node: document.querySelector('main')
})
```

```elm
-- Main.elm

import Browser
import Html exposing (h1, text)

main =
  h1 [] [ text "Hello, Elm!" ]
```

To learn more about Elm and its ecosystem of tools, see the official
[guide](https://guide.elm-lang.org/).

---

## File: src/i18n/ja/docs/env.md

# 🌳 Environment Variables

Parcel uses [dotenv](https://github.com/motdotla/dotenv) to support loading environment variables from `.env` files.

`.env` files are to be stored alongside the `package.json` that contains your `parcel-bundler` dependency.

Parcel loads `.env` files with these specific names for the following `NODE_ENV` values:

| valid `.env` filenames   | `NODE_ENV=\*` | `NODE_ENV=test` |
| ------------------------ | ------------- | --------------- |
| `.env`                   | ✔️            | ✔️              |
| `.env.local`             | ✔️            | ✖️              |
| `.env.${NODE_ENV}`       | ✔️            | ✔️              |
| `.env.${NODE_ENV}.local` | ✔️            | ✔️              |

Notably:

- `NODE_ENV` defaults to `development`.
- `.env.local` is not loaded when `NODE_ENV=test` since [tests should produce the same results for everyone](https://github.com/parcel-bundler/parcel/blob/28df546a2249b6aac1e529dd629f506ba6b0a4bb/src/utils/env.js#L9)

---

## File: src/i18n/ja/docs/getting_started.md

# 🚀 はじめに

Parcel は、開発者の経験によって生まれた Web アプリケーションバンドラです。設定不要で、マルチコア処理を利用した驚異的な高速パフォーマンスを提供します。

まずは yarn または npm で Parcel をインストールしましょう。

Yarn:

```bash
yarn global add parcel-bundler
```

npm:

```bash
npm install -g parcel-bundler
```

プロジェクトルートに以下のコマンドを使って package.json を作成しましょう。

```bash
yarn init -y
```

または

```bash
npm init -y
```

Parcel はどんな種類のファイルでもエントリーポイントとして扱うことができますが、HTML または JavaScript ファイルから始めるのがよいでしょう。HTML ファイルから相対パスでメインとなる JavaScript ファイルをリンクすると、Parcel はそれを処理し、参照を出力したファイルの URL に置き換えます。

次に、index.html と index.js ファイルを作成しましょう。

```html
<html>
  <body>
    <script src="./index.js"></script>
  </body>
</html>
```

```javascript
console.log('hello world')
```

Parcel には開発用サーバーが組み込まれており、ファイルを変更した際に自動的にアプリケーションを再ビルドします。 また、開発を効率的にするため[ホットモジュールリプレイスメント](hmr.html)をサポートしています。次のようにエントリーファイルを指定してみましょう。

```bash
parcel index.html
```

では、ブラウザで http://localhost:1234/ を開いてみましょう。もし、ホットモジュールリプレイスメントが動いていない場合は[エディタの設定を編集](hmr.html#safe-write)する必要があるかもしれません。 `-p <ポート番号>` オプションを使うことでデフォルトのポート番号を上書きすることができます。

自分でサーバーを持っていない場合、あるいはアプリケーションがすべてクライアントでレンダリングされる場合には、Parcel の開発用サーバを使いましょう。自分でサーバーを持っている場合には、代わりに Parcel を `watch` モードで実行することができます。ファイルが変更されると自動で再ビルドを行い、ホットモジュールリプレースメントをサポートしますが、Web サーバーは起動しません。

```bash
parcel watch index.html
```

### 複数のエントリーファイル

万が一、あなたが複数のエントリーファイルを持っている、たとえば `index.html` と `about.html` があるとした場合にはバンドラーを起動するために 2 種類の方法があります。

ファイル名を指定する方法

```bash
parcel index.html about.html
```

トークンを使って glob を作る方法

```bash
parcel *.html
```

_NOTE:_ もしこのようなファイル構造をしている場合

```
- folder-1
-- index.html
- folder-2
-- index.html
```

http://localhost:1234/folder-1/ を開いてもうまくいきません。http://localhost:1234/folder-1/index.html のように、ファイル名を正確に指定する必要があります。

### 本番用にビルドする

本番用のビルドを行うときは、 `build` モードがファイルの監視を無効にして、一度だけビルドを行います。 詳細は[本番](production.html)を参照してください。

### Parcel をプロジェクトに追加する

時には Parcel をグローバルインストールできないこともあるでしょう。（例：他人のマシンや CI を使ってプロジェクトを自動でビルドしたいとき）こういう場合には、ローカルパッケージとして Parcel をインストールすることができます。

yarn でインストールする方法

```bash
yarn add parcel-bundler --dev
```

npm でインストールする方法

```bash
npm install parcel-bundler --save-dev
```

それから、プロジェクトの `package.json` にこれらのタスクスクリプトを追加します。

```json
{
  "scripts": {
    "dev": "parcel <your entry file>",
    "build": "parcel build <your entry file>"
  }
}
```

すると、以下のように実行することができるようになります

```bash
# 開発モードで起動する
yarn dev
#または
npm run dev

# 本番モードでビルドする
yarn build
#または
npm run build
```

---

## File: src/i18n/ja/docs/graphQL.md

# GraphQL

_Supported extensions: `gql`, `graphql`_

---

## File: src/i18n/ja/docs/hmr.md

# 🔥 Hot Module Replacement

Hot Module Replacement (HMR) improves the development experience by automatically updating modules in the browser at runtime without needing a whole page refresh. This means that application state can be retained as you change small things. Parcel's HMR implementation supports both JavaScript and CSS assets out of the box. HMR is automatically disabled when bundling in production mode.

As you save files, Parcel rebuilds what changed and sends an update to any running clients containing the new code. The new code then replaces the old version, and is re-evaluated along with all parents. You can hook into this process using the `module.hot` API, which can notify your code when a module is about to be disposed, or when a new version comes in. Projects like [react-hot-loader](https://github.com/gaearon/react-hot-loader) can help with this process, and work out of the box with Parcel.

There are two methods to know about: `module.hot.accept` and `module.hot.dispose`. You call `module.hot.accept` with a callback function which is executed when that module or any of its dependencies are updated. `module.hot.dispose` accepts a callback which is called when that module is about to be replaced.

```javascript
if (module.hot) {
  module.hot.dispose(function() {
    // module is about to be replaced
  })

  module.hot.accept(function() {
    // module or one of its dependencies was just updated
  })
}
```

## Automagically installed dependencies

Whenever Parcel comes across a dependency that fits the `node_module` pattern and can't find it, Parcel tries to install this dependency using `yarn` or `npm` depending on finding a `yarn.lock` file or not. This prevents the developer from having to exit parcel or having multiple terminal windows open.

This only occurs in _development_ (using [`serve`](cli.md#serve) or [`watch`](cli.md#watch)), however in production (using [`build`](cli.md#build)) autoinstall is disabled to prevent unwanted side-effects on deployment.

You can disable this feature using [`--no-autoinstall`](cli.md#disable-autoinstall).

## Safe Write

Some text editors and IDE's have a feature called `safe write` that basically prevents data loss, by taking a copy of the file and renaming it when saved.

When using Hot Module Reload (HMR) this feature blocks the automatic detection of file updates, to disable `safe write` use the options provided below:

- `Sublime Text 3` add `atomic_save: "false"` to your user preferences.
- `IntelliJ` use search in the preferences to find "safe write" and disable it.
- `Vim` add `:set backupcopy=yes` to your settings.
- `WebStorm` uncheck `Use "safe write"` in Preferences > Appearance & Behavior > System Settings.

---

## File: src/i18n/ja/docs/how_it_works.md

# 🛠 How It Works

Parcel transforms a tree of **assets** to a tree of **bundles**. Many other bundlers are fundamentally based around JavaScript assets, with other formats tacked on - e.g. inlined as strings into JS files. Parcel is file-type agnostic - it will work with any type of assets the way you'd expect, with no configuration. There are three steps to Parcel's bundling process.

### 1. Constructing the Asset Tree

Parcel takes as input a single entry asset, which could be any type: a JS file, HTML, CSS, image, etc. There are various [asset types](asset_types.html) defined in Parcel which know how to handle specific file types. The assets are parsed, their dependencies are extracted, and they are transformed to their final compiled form. This creates a tree of assets.

### 2. Constructing the Bundle Tree

Once the asset tree has been constructed, the assets are placed into a bundle tree. A bundle is created for the entry asset, and child bundles are created for dynamic `import()`s, which cause code splitting to occur.

Sibling bundles are created when assets of a different type are imported, for example if you imported a CSS file from JavaScript, it would be placed into a sibling bundle to the corresponding JavaScript.

If an asset is required in more than one bundle, it is hoisted up to the nearest common ancestor in the bundle tree so it is not included more than once.

### 3. Packaging

After the bundle tree is constructed, each bundle is written to a file by a [packager](packagers.html) specific to the file type. The packagers know how to combine the code from each asset together into the final file that is loaded by a browser.

---

## File: src/i18n/ja/docs/html.md

# HTML

_Supported extensions: `htm`, `html`_

HTML assets are often the entry file that you provide to Parcel, but can also be referenced by JavaScript files, e.g. to provide links to other pages. URLs to scripts, styles, media, and other HTML files are extracted and compiled as described above. The references are rewritten in the HTML so that they link to the correct output files. All filenames should be relative to the current HTML file.

```html
<html>
  <body>
    <!-- reference an image file -->
    <img src="./images/header.png" />

    <a href="./other.html">Link to another page</a>

    <!-- import a JavaScript bundle -->
    <script src="./index.js"></script>
  </body>
</html>
```

## Importing uncompiled assets

Adding links to files that Parcel can compile (e.g. JavaScript, TypeScript, SCSS, etc.) in HTML is supported. Parcel will automatically process the file and update the link to point to the compiled asset.

```html
<html>
  <head>
    <!-- include a SCSS file -->
    <link rel="stylesheet" href="./my-styles/style.scss" />
  </head>
</html>
```

# PostHTML

[PostHTML](https://github.com/posthtml/posthtml) is a tool for transforming HTML with plugins. You can configure PostHTML with Parcel by creating a configuration file using one of these names: `.posthtmlrc` (JSON), `.posthtmlrc.js`, or `posthtml.config.js`.

Install plugins in your app:

```bash
yarn add posthtml-img-autosize
```

Then, create a `.posthtmlrc`:

```json
{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}
```

Plugins are specified in the `plugins` object as keys, and options are defined using object values. If there are no options for a plugin, just set it to `true` instead.

---

## File: src/i18n/ja/docs/javascript.md

# JavaScript

_Supported extensions: `js`, `jsx`, `es6`, `jsm`, `mjs`_

The most traditional file type for web bundlers is JavaScript. Parcel supports both CommonJS and ES6 module syntax for importing files. It also supports dynamic `import()` function syntax to load modules asynchronously, which is discussed in the [Code Splitting](code_splitting.html) section. Dynamic imports can also import modules from URLs.

```javascript
// Import a module using CommonJS syntax
const dep = require('./path/to/dep')

// Import a module using ES6 import syntax
import dep from './path/to/dep'

// Import a module from a URL (e.g. CDN), using dynamic imports
import('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js').then(() => {
  console.log(_.VERSION)
})
```

You can also import non-JavaScript assets from a JavaScript file, e.g. CSS, HTML or even an image file. When you import one of these files, it is not inlined as in some other bundlers. Instead, it is placed in a separate bundle (e.g. a CSS file) along with all of its dependencies. When using [CSS Modules](https://github.com/css-modules/css-modules), the exported classes are placed in the JavaScript bundle. Other asset types export a URL to the output file in the JavaScript bundle so you can reference them in your code.

```javascript
// Import a CSS file
import './test.css'

// Import a CSS file with CSS modules
import classNames from './test.css'

// Import the URL to an image file
import imageURL from './test.png'

// Import an HTML file
import('./some.html')
// or:
import html from './some.html'
// or:
require('./some.html')
```

If you want to inline a file into the JavaScript bundle instead of reference it by URL, you can use the Node.js `fs.readFileSync` API to do that. The URL must be statically analyzable, meaning it cannot have any variables in it (other than `__dirname` and `__filename`).

```javascript
import fs from 'fs'

// Read contents as a string
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Read contents as a Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')

// Convert Buffer contents to an image
;<img src={`data:image/png;base64,${buffer.toString('base64')}`} />
```

### Images in JSX

Below is an example of how you could import an image file for use in JSX.

```js
// Import the image file
import megaMan from "./images/mega-man.png";

// JSX
<img src={megaMan} title="Mega Man" alt="Mega Man" />

// JSX (w/ custom path)
<img src={`/dist${megaMan}`} title="Mega Man" alt="Mega Man" />
```

# Babel

[Babel](https://babeljs.io) is a popular transpiler for JavaScript, with a large plugin ecosystem. Using Babel with Parcel works the same way as using it standalone or with other bundlers.

Install presets and plugins in your app:

```shell
yarn add @babel/preset-react
```

Then, create a `.babelrc`:

```json
{
  "presets": ["@babel/preset-react"]
}
```

You can also put `babel` config in `package.json`

```json
"babel": {
  "presets": ["@babel/preset-react"]
}
```

NOTE: `package.json` takes precedence over `.babelrc`.

## Default Babel transforms

Parcel transpiles your code with `@babel/preset-env` by default, this is to transpile every module both internal (local requires) and external (node_modules) to match the defined target.

For the `browser` target it utilises [browserslist](https://github.com/browserslist/browserslist), the target browserlist can be defined in `package.json` (`engines.browsers` or `browserslist`) or using a configuration file (`browserslist` or `.browserslistrc`).

The browserlist target defaults to: `> 0.25%` (Meaning, support every browser that has 0.25% or more of the total amount of active web users)

For the `node` target, Parcel uses the `engines.node` defined in `package.json`, this default to _node 8_.

# Flow

[Flow](https://flow.org/) is a popular static type checker for JavaScript. Using Flow with Parcel is as simple as placing `// @flow` as the first line of your `js` files.

Parcel will automatically install the required Babel config to strip the Flow types from the compiled output, so there's nothing you have to worry about except [editor integrations](https://flow.org/en/docs/editors/) or supporting [Absolute Path module resolution](module_resolution.html#flow-with-absolute-or-tilde-resolution) with `.flowconfig`.

---

## File: src/i18n/ja/docs/json.md

# JSON

_Supported extensions: `json`, `json5`_

---

## File: src/i18n/ja/docs/less.md

# LESS

_Supported extensions: `less`_

It's not even necessary to install less 😱, parcel will automatically install less if it detects a less file.

You can import LESS files from JavaScript or html files.

```javascript
import './custom.less'
```

or

```html
<link href="./custom.less" rel="stylesheet" />
```

---

## File: src/i18n/ja/docs/meta.json

{
  "*": {
    "language": "en"
  }
}

---

## File: src/i18n/ja/docs/module_resolution.md

# 📔 Module Resolution

The Parcel resolver implements a modified version of [the node_modules resolution](https://nodejs.org/api/modules.html#modules_all_together) algorithm.

## Module resolution

In addition to the standard algorithm, all [asset types supported by Parcel](https://parceljs.org/assets.html) are also resolved.

Module resolution can be relative to the:

- **entry root**: the directory of the entrypoint specified to Parcel, or the shared root (common parent directory) when multiple entrypoints are specified.
- **package root**: the directory of the nearest module root in `node_modules`.

### Absolute Paths

`/foo` resolves `foo` relative to the **entry root**.

### ~ Tilde Paths

`~/foo` resolves `foo` relative to the nearest **package root** or, if not found, the **entry root**.

### Glob file paths

Globs are wildcard imports that bundle multiple assets at once. Globs can match some or all files (`/assets/*.png`), as well as files in multiple directories (`/assets/**/*`);

This example bundles a directory of png files and returns the dist URLs.

```
import foo from "/assets/*.png";
// {
//   'file-1': '/file-1.8e73c985.png',
//   'file-2': '/file-1.8e73c985.png'
// }
```

### package.json `browser` field

If a package includes a [package.browser field](https://docs.npmjs.com/files/package.json#browser), Parcel will use this instead of the package.main entry.

### Aliases

Aliases are supported through the `alias` field in `package.json`.

This example aliases `react` to `preact` and some local custom module that is not in `node_modules`.

```json
// package.json
{
  "name": "some-package",
  "devDependencies": {
    "parcel-bundler": "^1.7.0"
  },
  "alias": {
    "react": "preact-compat",
    "react-dom": "preact-compat",
    "local-module": "./custom/modules"
  }
}
```

Avoid using any special characters in your aliases as some may be used by Parcel and others by 3rd party tools or extensions. For example:

- `~` used by Parcel to resolve [tilde paths](#~-tilde-paths).
- `@` used by npm to resolve npm organisations.

We advise being explicit when defining your aliases, so please **specify file extensions**, otherwise Parcel will need to guess. See [JavaScript Named Exports](#javascript-named-exports) for an example of this.

## Common issues

### JavaScript Named Exports

Alias mappings apply to many asset types and do not specifically support mapping of JavaScript named exports. If you wish to map JS named exports you can do this:

```json
// package.json
{
  "name": "some-package",
  "alias": {
    "ipcRenderer": "./electron-ipc.js" // specify file extension
  }
}
```

and re-export the named export within the aliased file:

```js
// electron-ipc.js
module.exports = require('electron').ipcRenderer
```

### Flow with Absolute or Tilde Resolution

When using absolute path or tilde path module resolution you must configure Flow using the [module.name_mapper](https://flow.org/en/docs/config/options/#toc-module-name-mapper-regex-string) feature.

Given a project with this structure:

```
package.json
.flowconfig
src/
  index.html
  index.js
  components/
    apple.js
    banana.js
```

And `src/index.html` as an entrypoint, our **entry root** is the `src/` folder.

Therefore, to map this import correctly:

```javascript
// index.js
import Apple from '/components/apple'
```

We need Flow to replace the leading `/` in `'/components/apple'` with `src/`, resulting in `'src/components/apple'`.

The following setting in our `.flowconfig` achieves this replacement:

```
[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/src/\1'
```

Where `` is a Flow specific identifier indicating the location of our `.flowconfig`

NB: `module.name_mapper` can have multiple entries. This allows support for [Absolute](module_resolution.html#absolute-paths) or [Tilde](module_resolution.html#~-tilde-paths) Path Resolution in addition to [local module aliasing](module_resolution.html#aliasing) support.

### TypeScript ~ Resolution

TypeScript will need to know about your use of the `~` module resolution or alias mappings. Please refer to the [TypeScript Module Resolution docs](https://www.typescriptlang.org/docs/handbook/module-resolution.html) for further information.

```json
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~*": ["./src/*"]
    }
  }
}
```

### Monorepo Resolution

These are the advised usages with monorepos at this time:

Advised usage:

- use relative paths.
- use `/` for a root path if a root is required.

Unadvised usage:

- **avoid** `~` use within monorepos.

If you're a monorepo user and would like to contribute to these recommendations, please provide example repos when opening issues to support the discussion.

---

## File: src/i18n/ja/docs/openGL.md

# OpenGL Shading Language (GLSL)

_Supported extensions: `glsl`, `vert`, `frag`_

---

## File: src/i18n/ja/docs/packagers.md

# 📦 Packagers

In Parcel, a `Packager` combines multiple `Asset`s together into a final output bundle. This happens in the main process after all assets have been processed, and a bundle tree has been created. Packagers are registered based on output file type, and assets that have generated that output type are sent to that packager for production of the final output file.

## Packager Interface

```javascript
const { Packager } = require('parcel-bundler')

class MyPackager extends Packager {
  async start() {
    // optional. write file header if needed.
    await this.dest.write(header)
  }

  async addAsset(asset) {
    // required. write the asset to the output file.
    await this.dest.write(asset.generated.foo)
  }

  async end() {
    // optional. write file trailer if needed.
    await this.dest.end(trailer)
  }
}

module.exports = MyPackager
```

## Registering a Packager

You can register your packager with a bundler using the `addPackager` method. It accepts a file type to register, and the path to your packager module.

```javascript
const Bundler = require('parcel-bundler')

let bundler = new Bundler('input.js')
bundler.addPackager('foo', require.resolve('./MyPackager'))
```

---

## File: src/i18n/ja/docs/plugins.md

# 🔌 Plugins

Parcel takes a slightly different approach from many other tools in that many common formats are included out of the box without the need to install and configure additional plugins. However, there are cases where you might want to extend Parcel in a nonstandard way, and for those times, plugins are supported. Installed plugins are automatically detected and loaded based on `package.json` dependencies.

When adding support for a new file format to Parcel, you should first consider how widespread it is, and how standardized the implementation is. If it is sufficiently widespread and standard, the format should probably be added to Parcel core rather than as a plugin that users need to install. If you have any doubts, [GitHub](https://github.com/parcel-bundler/parcel/issues) is the right place to discuss.

## Plugin API

Parcel plugins are very simple. They are simply modules that export a single function, which is called by Parcel automatically during initialization. The function receives as input the `Bundler` object, and can do configuration such as registering asset types and packagers.

```javascript
module.exports = function(bundler) {
  bundler.addAssetType('ext', require.resolve('./MyAsset'))
  bundler.addPackager('foo', require.resolve('./MyPackager'))
}
```

Publish this package on npm using `parcel-plugin-` or `@your-scope/parcel-plugin-` prefixes, and it will be automatically detected and loaded as described below.

## Using Plugins

Using plugins in Parcel could not be any simpler. All you need to do is install and save them in your `package.json`. Plugins should be named with the prefix `parcel-plugin-` or `@your-scope/parcel-plugin-`, e.g. `parcel-plugin-foo` or `@your-scope/parcel-plugin-foo`. Any dependencies listed in `package.json` with these prefixes will automatically be loaded during initialization.

---

## File: src/i18n/ja/docs/production.md

# ✨ Production

When it comes time to bundle your application for production, you can use Parcel's production mode.

```bash
parcel build entry.js
```

## Optimisations

This disables watch mode and hot module replacement so it will only build once. It also enables the minifier for all output bundles to reduce file size. The minifiers used by Parcel are [terser](https://github.com/fabiosantoscode/terser) for JavaScript, [cssnano](http://cssnano.co) for CSS, and [htmlnano](https://github.com/posthtml/htmlnano) for HTML.

Enabling production mode also sets the `NODE_ENV=production` environment variable. Large libraries like React have development-only debugging features which are disabled by setting this environment variable, which results in smaller and faster builds for production.

To take advantage of the same kind of development-only debugging features, ensure that [terser's `dead_code` option](https://github.com/terser-js/terser#compress-options) is on (it is by default) and wrap any development-only debugging in a conditional check like so:

```js
if (process.env.NODE_ENV === 'development') {
  // Or, `process.env.NODE_ENV !== 'production'`
  // Only runs in development and will be stripped from production build.
}
```

## File naming strategy

To allow setting very aggresive caching rules to your cdn, for optimal performance and efficiency, Parcel hashes the file names of most bundles (according to whether the bundle should have a readable/rememberable name or not, mainly for SEO).

Parcel follows the following table, when it comes to naming bundles. (Entrypoints are never hashed)

|                   Bundle Type | Type               | Content hashed |
| ----------------------------: | ------------------ | :------------: |
|                           Any | Entrypoint         |       ❌       |
|                    JavaScript | `<script>`         |       ✅       |
|                    JavaScript | Dynamic import     |       ❌       |
|                    JavaScript | Service worker     |       ❌       |
|                          HTML | iframe             |       ❌       |
|                          HTML | anchor link        |       ❌       |
| Raw (Images, text files, ...) | Import/Require/... |       ✅       |

The file hash follows the following naming pattern: `<directory name>-<hash>.<extension>`

## Cross platform gotchas

In an effort to optimize production build performance, Parcel will try to determine the number of CPUs available at the machine running the build command so it can distribute the work accordingly. To do so, Parcel relies on the [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count) library.

Be aware that this module assumes you have the [`lscpu`](http://manpages.courier-mta.org/htmlman1/lscpu.1.html) program available in your system.

## Using a CI

If you want to integrate Parcel in your Continuous Integration system (e.g. Travis or Circle CI), you might need to install Parcel as a local dependency.

The instructions can be [found here](getting_started.html#adding-parcel-to-your-project).

---

## File: src/i18n/ja/docs/pug.md

# Pug

_Supported extensions: `jade`, `pug`_

---

## File: src/i18n/ja/docs/reasonML.md

# ReasonML

_Supported extensions: `ml`, `re`_

## ReasonML/BuckleScript

[ReasonML](https://reasonml.github.io/) compiles OCaml to JavaScript with the help of [BuckleScript](https://bucklescript.github.io). You can use ReasonML by installing dependencies and creating `bsconfig.json`:

```bash
$ yarn add bs-platform --dev
```

```json
// bsconfig.json
// from https://github.com/BuckleScript/bucklescript/blob/master/jscomp/bsb/templates/basic-reason/bsconfig.json

{
  "name": "whatever",
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```html
<!-- index.html -->
<!DOCTYPE html>
<html>
  <body>
    <script src="./src/index.re"></script>
  </body>
</html>
```

```reason
/* src/index.re */
print_endline("Hello World");
```

### ReasonReact

[ReasonReact](https://reasonml.github.io/reason-react/) is React binding for ReasonML. You can use it with Parcel too:

```bash
$ yarn add react react-dom reason-react
```

```diff
// bsconfig.json

{
  "name": "whatever",
+ "reason": {
+   "react-jsx": 2
+ },
  "sources": {
    "dir": "src",
    "subdirs": true
  },
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  },
  "suffix": ".bs.js",
  "bs-dependencies": [
+   "reason-react"
  ],
  "warnings": {
    "error": "+101"
  },
  "namespace": true,
  "refmt": 3
}
```

```diff
<!-- index.html -->
<html>
<body>
+  <div id="app"></div>
  <script src="./src/index.re"></script>
</body>
</html>
```

```reason
/* src/Greeting.re */

let component = ReasonReact.statelessComponent("Greeting");

let make = (~name, _children) => {
  ...component,
  render: _self => <div> (ReasonReact.string("Hello! " ++ name)) </div>,
};
```

```reason
/* src/index.re */

ReactDOMRe.renderToElementWithId(<Greeting name="Parcel" />, "app");
```

--- METRICS ---
- Files Extracted: 127
- Estimated Token Budget: ~68263 tokens
- Recency Window: Active (< 180 days)
- Canonical Reference: https://codewiki.google/github.com/wesbos/JavaScript30
