diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..c6c8b3621 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/package.json b/package.json index 40817ea22..280446ecd 100644 --- a/package.json +++ b/package.json @@ -6,17 +6,26 @@ "repository": "git://git@github.com:parcel-bundler/website.git", "author": "Devon Govett ", "license": "MIT", - "dependencies": { - "express": "^4.16.2" - }, - "devDependencies": { - "markdown-styles": "^3.1.10", - "now": "^11.2.4" - }, "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" } } diff --git a/prettier.config.js b/prettier.config.js new file mode 100644 index 000000000..db9ff30b7 --- /dev/null +++ b/prettier.config.js @@ -0,0 +1,5 @@ +module.exports = { + printWidth: 120, + semi: false, + singleQuote: true +} diff --git a/src/assets/home.css b/src/assets/home.css index c28d2e1c6..ece30894d 100644 --- a/src/assets/home.css +++ b/src/assets/home.css @@ -1,31 +1,53 @@ -html, body { +html, +body { margin: 0; padding: 0; min-width: 250px; - font-family:Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; - background:#fefefe; + font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; + background: #fefefe; } -h1,h2,h3,h4,h5,h6{ -font-weight:400; -color:#111; -line-height:1em; -font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: 400; + color: #111; + line-height: 1em; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; +} +h4, +h5, +h6 { + font-weight: bold; +} +h1 { + font-size: 3.2em; +} +h2 { + font-size: 2em; +} +h3 { + font-size: 1.5em; +} +h4 { + font-size: 1.2em; +} +h5 { + font-size: 1em; +} +h6 { + font-size: 0.9em; } -h4,h5,h6{ font-weight: bold; } -h1{ font-size:3.2em; } -h2{ font-size:2em; } -h3{ font-size:1.5em; } -h4{ font-size:1.2em; } -h5{ font-size:1em; } -h6{ font-size:0.9em; } header { - background: #21374B; - color: #E7DACB; + background: #21374b; + color: #e7dacb; text-align: center; padding: 80px 0 50px 0; - font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; } .logo { @@ -37,7 +59,7 @@ header { header .subtitle { margin: 0; font-size: 1.5em; - color: #E7DACB; + color: #e7dacb; } .parcel { @@ -99,11 +121,11 @@ header .subtitle { display: inline-block; padding: 8px 0; width: 180px; - color: #E7DACB; - border: 1px solid #E7DACB; + color: #e7dacb; + border: 1px solid #e7dacb; border-radius: 50px; text-decoration: none; - font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 20px; transition: opacity 200ms; text-align: center; @@ -115,8 +137,8 @@ header .subtitle { } .get-started { - background: #E7DACB; - color: #21374B; + background: #e7dacb; + color: #21374b; } header .links { @@ -125,11 +147,11 @@ header .links { right: 0; display: flex; margin: 20px; - align-items: center; + align-items: center; } header .links a { - color: #E7DACB; + color: #e7dacb; text-decoration: none; padding-left: 20px; transition: color 125ms; @@ -159,9 +181,9 @@ header .links a:hover { main { max-width: 1000px; margin: 0 auto; - color:#444; - font-size:16px; - line-height:1.5em; + color: #444; + font-size: 16px; + line-height: 1.5em; } main section { @@ -185,8 +207,20 @@ main > section { padding: 0 20px; } -pre, code, kbd, samp { color: #000; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 0.98em; } -pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; font-size: 12px; } +pre, +code, +kbd, +samp { + color: #000; + font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 0.98em; +} +pre { + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; + font-size: 12px; +} p code { font-size: 0.95em; @@ -205,7 +239,8 @@ tr:nth-child(2n + 1) { background: #efefef; } -td, th { +td, +th { padding: 5px 10px; text-align: left; border: 1px solid #ddd; @@ -226,9 +261,9 @@ td, th { } footer { - background: #21374B; - color: #E7DACB; - font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + background: #21374b; + color: #e7dacb; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; padding: 40px 0 20px 0; margin-top: 40px; text-align: center; @@ -252,7 +287,7 @@ footer nav ul { footer nav a, footer .copyright a { - color: #E7DACB; + color: #e7dacb; text-decoration: none; transition: color 125ms; line-height: 1.7em; @@ -273,7 +308,7 @@ footer h3 { text-transform: uppercase; font-size: 13px; opacity: 0.7; - color: #E7DACB; + color: #e7dacb; } footer .copyright { diff --git a/src/assets/icons.js b/src/assets/icons.js index 7e8d83ec2..5ed6e1b98 100644 --- a/src/assets/icons.js +++ b/src/assets/icons.js @@ -1,19 +1,4 @@ -var icons = [ - 'js', - 'json', - 'css', - 'sass', - 'less', - 'html', - 'jpg', - 'png', - 'gif', - 'bmp', - 'svg', - 'raw', - 'rs', - 'ts' -] +var icons = ['js', 'json', 'css', 'sass', 'less', 'html', 'jpg', 'png', 'gif', 'bmp', 'svg', 'raw', 'rs', 'ts'] var container = document.querySelector('.icons') @@ -23,11 +8,7 @@ function spawn() { svg.style.left = 25 + Math.random() * 50 + '%' svg.setAttribute('class', 'icon') var use = document.createElementNS('http://www.w3.org/2000/svg', 'use') - use.setAttributeNS( - 'http://www.w3.org/1999/xlink', - 'href', - 'assets/icons.svg#' + icon, - ) + use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'assets/icons.svg#' + icon) svg.appendChild(use) container.appendChild(svg) diff --git a/src/assets/pilcrow.css b/src/assets/pilcrow.css index 81d85250b..a41c55ec9 100644 --- a/src/assets/pilcrow.css +++ b/src/assets/pilcrow.css @@ -13,9 +13,9 @@ h3:hover .header-link:before, h4:hover .header-link:before, h5:hover .header-link:before, h6:hover .header-link:before { - content: "\00B6";/* pilcrow */ - color: #888; - font-size: smaller; + content: '\00B6'; /* pilcrow */ + color: #888; + font-size: smaller; } .header-link { diff --git a/src/assets/style.css b/src/assets/style.css index 7504af8d1..0912fbbba 100644 --- a/src/assets/style.css +++ b/src/assets/style.css @@ -1,18 +1,27 @@ -html { height: 100%; font-size: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } - -body{ -color:#444; -font-family:Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; -font-size:12px; -line-height:1.5em; -padding:0; -margin: 0; -background:#fefefe; -box-sizing: border-box; -width: 100%; +html { + height: 100%; + font-size: 100%; + overflow-y: auto; + -webkit-overflow-scrolling: touch; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} + +body { + color: #444; + font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; + font-size: 12px; + line-height: 1.5em; + padding: 0; + margin: 0; + background: #fefefe; + box-sizing: border-box; + width: 100%; } -*, *:before, *:after { +*, +*:before, +*:after { box-sizing: inherit; } @@ -20,14 +29,14 @@ header { position: -webkit-sticky; position: sticky; top: 0; - background: #21374B; - color: #E7DACB; + background: #21374b; + color: #e7dacb; display: flex; justify-content: space-between; align-items: center; height: 50px; z-index: 500; - font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; } header .logo { @@ -50,7 +59,7 @@ header .links { } header .links a { - color: #E7DACB; + color: #e7dacb; text-decoration: none; padding-left: 20px; transition: color 125ms; @@ -83,7 +92,7 @@ header .links a:hover { max-width: 1280px; min-height: 100%; margin: 0 auto; - padding:1em; + padding: 1em; } .search-input { @@ -92,16 +101,16 @@ header .links a:hover { width: 90px; border: none; border-radius: 50px; - font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: inherit; margin: 0 20px; transition: all 250ms; background: rgba(255, 255, 255, 0); - color: #E7DACB; + color: #e7dacb; } .search-input::placeholder { - color: #E7DACB; + color: #e7dacb; } .search-input:hover { @@ -116,7 +125,7 @@ header .links a:hover { nav { width: 250px; - font-family: "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; border-right: 1px solid #eee; position: -webkit-sticky; @@ -124,8 +133,8 @@ nav { align-self: flex-start; height: calc(100vh - 50px - 2em); top: calc(50px + 1em); - overflow:hidden; - overflow-y:scroll; + overflow: hidden; + overflow-y: scroll; } nav ul { @@ -173,44 +182,99 @@ main { margin: 0 auto; } -a{ color: #0645ad; text-decoration:none;} -a:visited{ color: #0645ad; } -a:hover{ color: #06e; } -a:active{ color:#faa700; } -a:focus{ outline: thin dotted; } -a:hover, a:active{ outline: 0; } +a { + color: #0645ad; + text-decoration: none; +} +a:visited { + color: #0645ad; +} +a:hover { + color: #06e; +} +a:active { + color: #faa700; +} +a:focus { + outline: thin dotted; +} +a:hover, +a:active { + outline: 0; +} -p{ -margin:1em 0; +p { + margin: 1em 0; } -img{ -max-width:100%; +img { + max-width: 100%; } -h1,h2,h3,h4,h5,h6{ -font-weight:400; -color:#111; -line-height:1em; -font-family: "Gill Sans", "Avenir Next", Avenir, "Helvetica Neue", Helvetica, Arial, sans-serif; +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: 400; + color: #111; + line-height: 1em; + font-family: 'Gill Sans', 'Avenir Next', Avenir, 'Helvetica Neue', Helvetica, Arial, sans-serif; +} +h4, +h5, +h6 { + font-weight: bold; +} +h1 { + font-size: 3.2em; +} +h2 { + font-size: 2em; +} +h3 { + font-size: 1.5em; +} +h4 { + font-size: 1.2em; +} +h5 { + font-size: 1em; +} +h6 { + font-size: 0.9em; } -h4,h5,h6{ font-weight: bold; } -h1{ font-size:3.2em; } -h2{ font-size:2em; } -h3{ font-size:1.5em; } -h4{ font-size:1.2em; } -h5{ font-size:1em; } -h6{ font-size:0.9em; } -blockquote{ -color:#666666; -margin:0; -padding-left: 3em; -border-left: 0.5em #EEE solid; +blockquote { + color: #666666; + margin: 0; + padding-left: 3em; + border-left: 0.5em #eee solid; +} +hr { + display: block; + height: 2px; + border: 0; + border-top: 1px solid #aaa; + border-bottom: 1px solid #eee; + margin: 1em 0; + padding: 0; +} +pre, +code, +kbd, +samp { + color: #000; + font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 0.98em; +} +pre { + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; + font-size: 12px; } -hr { display: block; height: 2px; border: 0; border-top: 1px solid #aaa;border-bottom: 1px solid #eee; margin: 1em 0; padding: 0; } -pre, code, kbd, samp { color: #000; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 0.98em; } -pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; font-size: 12px; } p code { font-size: 0.95em; @@ -220,34 +284,77 @@ p code { display: inline-block; } -p a code{ - color: #0645ad; text-decoration:none; +p a code { + color: #0645ad; + text-decoration: none; } -b, strong { font-weight: bold; } +b, +strong { + font-weight: bold; +} -dfn { font-style: italic; } +dfn { + font-style: italic; +} -ins { background: #ff9; color: #000; text-decoration: none; } +ins { + background: #ff9; + color: #000; + text-decoration: none; +} -mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; } +mark { + background: #ff0; + color: #000; + font-style: italic; + font-weight: bold; +} -sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } -sup { top: -0.5em; } -sub { bottom: -0.25em; } +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} +sup { + top: -0.5em; +} +sub { + bottom: -0.25em; +} -ul, ol { margin: 1em 0; padding: 0 0 0 2em; } -li p:last-child { margin:0 } -dd { margin: 0 0 0 2em; } +ul, +ol { + margin: 1em 0; + padding: 0 0 0 2em; +} +li p:last-child { + margin: 0; +} +dd { + margin: 0 0 0 2em; +} -img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; } +img { + border: 0; + -ms-interpolation-mode: bicubic; + vertical-align: middle; +} -table { border-collapse: collapse; border-spacing: 0; } -td { vertical-align: top; } +table { + border-collapse: collapse; + border-spacing: 0; +} +td { + vertical-align: top; +} -td, th { +td, +th { border: 1px solid #999; - padding: .5rem 1rem; + padding: 0.5rem 1rem; } @media only screen and (max-width: 952px) { @@ -269,7 +376,7 @@ td, th { z-index: 500; position: static; - overflow-y:hidden; + overflow-y: hidden; } nav ul { @@ -287,27 +394,78 @@ td, th { } @media only screen and (min-width: 480px) { -body{font-size:14px;} + body { + font-size: 14px; + } } @media only screen and (min-width: 768px) { -body{font-size:16px;} + body { + font-size: 16px; + } } @media print { - * { background: transparent !important; color: black !important; filter:none !important; -ms-filter: none !important; } - nav {display: none;} - body{font-size:12pt; max-width:100%;} - a, a:visited { text-decoration: underline; } - hr { height: 1px; border:0; border-bottom:1px solid black; } - a[href]:after { content: " (" attr(href) ")"; } - abbr[title]:after { content: " (" attr(title) ")"; } - .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } - pre, blockquote { border: 1px solid #999; padding-right: 1em; page-break-inside: avoid; } - tr, img { page-break-inside: avoid; } - img { max-width: 100% !important; } - @page :left { margin: 15mm 20mm 15mm 10mm; } - @page :right { margin: 15mm 10mm 15mm 20mm; } - p, h2, h3 { orphans: 3; widows: 3; } - h2, h3 { page-break-after: avoid; } + * { + background: transparent !important; + color: black !important; + filter: none !important; + -ms-filter: none !important; + } + nav { + display: none; + } + body { + font-size: 12pt; + max-width: 100%; + } + a, + a:visited { + text-decoration: underline; + } + hr { + height: 1px; + border: 0; + border-bottom: 1px solid black; + } + a[href]:after { + content: ' (' attr(href) ')'; + } + abbr[title]:after { + content: ' (' attr(title) ')'; + } + .ir a:after, + a[href^='javascript:']:after, + a[href^='#']:after { + content: ''; + } + pre, + blockquote { + border: 1px solid #999; + padding-right: 1em; + page-break-inside: avoid; + } + tr, + img { + page-break-inside: avoid; + } + img { + max-width: 100% !important; + } + @page :left { + margin: 15mm 20mm 15mm 10mm; + } + @page :right { + margin: 15mm 10mm 15mm 20mm; + } + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + h2, + h3 { + page-break-after: avoid; + } } diff --git a/src/i18n/en/docs/api.md b/src/i18n/en/docs/api.md index 6a6e53423..5c85210db 100644 --- a/src/i18n/en/docs/api.md +++ b/src/i18n/en/docs/api.md @@ -4,6 +4,7 @@ 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'); @@ -55,7 +56,8 @@ runBundle(); 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 +- `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) => { @@ -65,7 +67,8 @@ bundler.on('bundled', (bundle) => { bundler.bundle(); ``` -* `buildEnd` gets called after each build (aka **including every rebuild**), this also emits if an error occurred +- `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', () => { @@ -75,7 +78,8 @@ bundler.on('buildEnd', () => { bundler.bundle(); ``` -* `buildStart` gets called at the start of the first build, the `entryFiles` Array gets passed to the callback +- `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 => { @@ -85,7 +89,8 @@ bundler.on('buildStart', entryPoints => { bundler.bundle(); ``` -* `buildError` gets called every time an error occurs during builds, the `Error` Object gets passed to the callback +- `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 => { @@ -101,21 +106,20 @@ A `Bundle` is what Parcel uses to bundle assets together, this also contains chi #### 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` of all sibling bundles -* `offsets`: A `Map` of all the locations of the assets inside the bundle, used to generate accurate source maps +- `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` of all sibling bundles +- `offsets`: A `Map` 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: @@ -158,6 +162,7 @@ index.html 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')(); diff --git a/src/i18n/en/docs/asset_types.md b/src/i18n/en/docs/asset_types.md index 17db40340..1ad84caed 100644 --- a/src/i18n/en/docs/asset_types.md +++ b/src/i18n/en/docs/asset_types.md @@ -7,14 +7,14 @@ Because Parcel processes assets in parallel across multiple processor cores, the ## Asset Interface ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // set the main output type. + type = 'foo' // set the main output type. async parse(code) { // parse code to an AST - return ast; + return ast } async pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // analyze dependencies - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { @@ -43,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', // alternative rendition to be placed in JS bundle if needed sourceMap } - ]; + ] } async postProcess(generated) { @@ -60,8 +60,8 @@ module.exports = MyAsset 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/en/docs/cli.md b/src/i18n/en/docs/cli.md index c22257414..0ba713b2d 100644 --- a/src/i18n/en/docs/cli.md +++ b/src/i18n/en/docs/cli.md @@ -137,12 +137,12 @@ Available in: `serve`, `watch`, `build` parcel entry.js --log-level 1 ``` -| Loglevel | Effect | -|--- |--- | -| 0 | Logging disabled | -| 1 | Only log errors | -| 2 | Log errors and warnings | -| 3 | Log everything | +| Loglevel | Effect | +| -------- | ----------------------- | +| 0 | Logging disabled | +| 1 | Only log errors | +| 2 | Log errors and warnings | +| 3 | Log everything | ### HMR Hostname diff --git a/src/i18n/en/docs/code_splitting.md b/src/i18n/en/docs/code_splitting.md index d2097a6a8..dc757c01a 100644 --- a/src/i18n/en/docs/code_splitting.md +++ b/src/i18n/en/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // Render the page } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Render page - page.render(); -}); + page.render() +}) ``` 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'); +const page = await import('./pages/about') // Render page -page.render(); +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. @@ -35,12 +36,12 @@ Dynamic imports are also lazily loaded in Parcel, so you can still put all your 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(); + const page = await pages[name] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +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). diff --git a/src/i18n/en/docs/coffeeScript.md b/src/i18n/en/docs/coffeeScript.md index 208c36e95..d665659cc 100644 --- a/src/i18n/en/docs/coffeeScript.md +++ b/src/i18n/en/docs/coffeeScript.md @@ -1,3 +1,3 @@ # CoffeeScript -*Supported extensions: `coffee`* +_Supported extensions: `coffee`_ diff --git a/src/i18n/en/docs/css.md b/src/i18n/en/docs/css.md index 26acd3253..302eb16be 100644 --- a/src/i18n/en/docs/css.md +++ b/src/i18n/en/docs/css.md @@ -1,6 +1,6 @@ # CSS -*Supported extensions: `css`, `pcss`, `postcss`* +_Supported extensions: `css`, `pcss`, `postcss`_ CSS assets can be imported from a JavaScript or HTML file, and 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. @@ -60,11 +60,14 @@ Parcel adds [cssnano](http://cssnano.co) to postcss in order to minify css in pr ```js module.exports = { - preset: ['default', { - calc: false, - discardComments: { - removeAll: true, + preset: [ + 'default', + { + calc: false, + discardComments: { + removeAll: true + } } - }] -}; + ] +} ``` diff --git a/src/i18n/en/docs/getting_started.md b/src/i18n/en/docs/getting_started.md index c4acc6f2e..8c511dacc 100644 --- a/src/i18n/en/docs/getting_started.md +++ b/src/i18n/en/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel is a web application bundler, differentiated by its developer experience. First install Parcel using Yarn or npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Create a package.json file in your project directory using: ```bash yarn init -y ``` -or + +or + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Next, create an index.html and index.js file. ``` ```javascript -console.log("hello world"); +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. Just point it at your entry file: @@ -59,16 +63,19 @@ parcel watch index.html 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: Specifing 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: +_NOTE:_ In case you have a file structure like this: + ``` - folder-1 -- index.html @@ -111,8 +118,7 @@ Then, add these tasks scripts to your project, by modifying your `package.json`: Then, you will be able to run it: -``` bash - +```bash # To run in development mode yarn dev #or @@ -122,5 +128,4 @@ npm run dev yarn build #or npm run build - ``` diff --git a/src/i18n/en/docs/graphQL.md b/src/i18n/en/docs/graphQL.md index beab896a4..67f2e9c43 100644 --- a/src/i18n/en/docs/graphQL.md +++ b/src/i18n/en/docs/graphQL.md @@ -1,3 +1,3 @@ # GraphQL -*Supported extensions: `gql`, `graphql`* +_Supported extensions: `gql`, `graphql`_ diff --git a/src/i18n/en/docs/hmr.md b/src/i18n/en/docs/hmr.md index c21db966f..9a38ddf67 100644 --- a/src/i18n/en/docs/hmr.md +++ b/src/i18n/en/docs/hmr.md @@ -8,13 +8,13 @@ There are two methods to know about: `module.hot.accept` and `module.hot.dispose ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // module is about to be replaced - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // module or one of its dependencies was just updated - }); + }) } ``` @@ -22,16 +22,17 @@ if (module.hot) { 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. +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` this 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. +- `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. diff --git a/src/i18n/en/docs/how_it_works.md b/src/i18n/en/docs/how_it_works.md index 750f771d3..a76068036 100644 --- a/src/i18n/en/docs/how_it_works.md +++ b/src/i18n/en/docs/how_it_works.md @@ -4,7 +4,7 @@ Parcel transforms a tree of **assets** to a tree of **bundles**. Many other bund ### 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. +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 diff --git a/src/i18n/en/docs/html.md b/src/i18n/en/docs/html.md index b378b8719..941215c6e 100644 --- a/src/i18n/en/docs/html.md +++ b/src/i18n/en/docs/html.md @@ -1,6 +1,6 @@ # HTML -*Supported extensions: `htm`, `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. @@ -19,7 +19,8 @@ HTML assets are often the entry file that you provide to Parcel, but can also be ``` ## 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. + +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 diff --git a/src/i18n/en/docs/javascript.md b/src/i18n/en/docs/javascript.md index 0d855cd1f..709d0ba42 100644 --- a/src/i18n/en/docs/javascript.md +++ b/src/i18n/en/docs/javascript.md @@ -1,28 +1,28 @@ # Javascript -*Supported extensions: `js`, `jsx`, `es6`, `jsm`, `mjs`* +_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. ```javascript // Import a module using CommonJS syntax -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // Import a module using ES6 import syntax -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` 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 './test.css' // Import a CSS file with CSS modules -import classNames from './test.css'; +import classNames from './test.css' // Import the URL to an image file -import imageURL from './test.png'; +import imageURL from './test.png' // Import an HTML file import('./some.html') @@ -35,16 +35,16 @@ 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'; +import fs from 'fs' // Read contents as a string -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Read contents as a Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') // Convert Buffer contents to an image - +; ``` # Babel @@ -61,9 +61,7 @@ Then, create a `.babelrc`: ```json { - "presets": [ - "@babel/preset-react" - ] + "presets": ["@babel/preset-react"] } ``` @@ -75,4 +73,4 @@ For the `browser` target it utilises [browserslist](https://github.com/browsersl 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*. +For the `node` target, Parcel uses the `engines.node` defined in `package.json`, this default to _node 8_. diff --git a/src/i18n/en/docs/json.md b/src/i18n/en/docs/json.md index 76f071f4f..b4577f700 100644 --- a/src/i18n/en/docs/json.md +++ b/src/i18n/en/docs/json.md @@ -1,3 +1,3 @@ # JSON -*Supported extensions: `json`, `json5`* +_Supported extensions: `json`, `json5`_ diff --git a/src/i18n/en/docs/less.md b/src/i18n/en/docs/less.md index f300459d1..d96c0cccb 100644 --- a/src/i18n/en/docs/less.md +++ b/src/i18n/en/docs/less.md @@ -1,3 +1,3 @@ # LESS -*Supported extensions: `less`* +_Supported extensions: `less`_ diff --git a/src/i18n/en/docs/meta.json b/src/i18n/en/docs/meta.json index b929ef3f4..b43d4c1de 100644 --- a/src/i18n/en/docs/meta.json +++ b/src/i18n/en/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "en" } -} \ No newline at end of file +} diff --git a/src/i18n/en/docs/module_resolution.md b/src/i18n/en/docs/module_resolution.md index 75b570b89..e5622b577 100644 --- a/src/i18n/en/docs/module_resolution.md +++ b/src/i18n/en/docs/module_resolution.md @@ -63,7 +63,7 @@ and re-export the named export within the aliased file: ```js // electron-ipc.js -module.exports = require("electron").ipcRenderer; +module.exports = require('electron').ipcRenderer ``` ### TypeScript ~ Resolution diff --git a/src/i18n/en/docs/openGL.md b/src/i18n/en/docs/openGL.md index 375bfc9bd..74773c46d 100644 --- a/src/i18n/en/docs/openGL.md +++ b/src/i18n/en/docs/openGL.md @@ -1,3 +1,3 @@ # OpenGL Shading Language (GLSL) -*Supported extensions: `glsl`, `vert`, `frag`* +_Supported extensions: `glsl`, `vert`, `frag`_ diff --git a/src/i18n/en/docs/packagers.md b/src/i18n/en/docs/packagers.md index 5db0d9dac..79112ef98 100644 --- a/src/i18n/en/docs/packagers.md +++ b/src/i18n/en/docs/packagers.md @@ -5,22 +5,22 @@ In Parcel, a `Packager` combines multiple `Asset`s together into a final output ## Packager Interface ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // optional. write file header if needed. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // required. write the asset to the output file. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // optional. write file trailer if needed. - await this.dest.end(trailer); + await this.dest.end(trailer) } } @@ -32,8 +32,8 @@ module.exports = MyPackager 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/en/docs/plugins.md b/src/i18n/en/docs/plugins.md index 59531af58..dbe6b296a 100644 --- a/src/i18n/en/docs/plugins.md +++ b/src/i18n/en/docs/plugins.md @@ -9,10 +9,10 @@ When adding support for a new file format to Parcel, you should first consider h 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')); -}; +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. diff --git a/src/i18n/en/docs/production.md b/src/i18n/en/docs/production.md index e502938c4..2a47a75e4 100644 --- a/src/i18n/en/docs/production.md +++ b/src/i18n/en/docs/production.md @@ -18,15 +18,15 @@ To allow setting very aggresive caching rules to your cdn, for optimal performan Parcel follows the following table, when it comes to naming bundles. (Entrypoints are never hashed) -| Bundle Type | Type | Content hashed | -| ---:| --- |:---:|:---:| -| Any | Entrypoint | ❌ | -| JavaScript | ` @@ -149,4 +149,4 @@ Add Start script to `package.json` } ``` -Done! 😄 Compiled `.js` file can be found inside the dist folder. \ No newline at end of file +Done! 😄 Compiled `.js` file can be found inside the dist folder. diff --git a/src/i18n/en/docs/rust.md b/src/i18n/en/docs/rust.md index a0de60717..40744cce8 100644 --- a/src/i18n/en/docs/rust.md +++ b/src/i18n/en/docs/rust.md @@ -1,6 +1,6 @@ # Rust -*Supported extensions: `rs`* +_Supported extensions: `rs`_ [Rust](https://www.rust-lang.org/en-US/) 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! @@ -10,11 +10,11 @@ Just like with `.wasm` files, `.rs` files can be imported with either synchronou ```js // synchronous import -import {add} from './add.rs'; -console.log(add(2, 3)); +import { add } from './add.rs' +console.log(add(2, 3)) // asynchronous import -const {add} = await import('./add.rs'); -console.log(add(2, 3)); +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. diff --git a/src/i18n/en/docs/scss.md b/src/i18n/en/docs/scss.md index 7eb207f5e..3710951ac 100644 --- a/src/i18n/en/docs/scss.md +++ b/src/i18n/en/docs/scss.md @@ -1,13 +1,17 @@ # SCSS -*Supported extensions: `sass`, `scss`* +_Supported extensions: `sass`, `scss`_ SCSS compilation needs `sass` (JS version of `dart-sass`) module. To install it with npm: + ```bash npm install 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. diff --git a/src/i18n/en/docs/stylus.md b/src/i18n/en/docs/stylus.md index cd2d65c5a..c42fd244b 100644 --- a/src/i18n/en/docs/stylus.md +++ b/src/i18n/en/docs/stylus.md @@ -1,3 +1,3 @@ # Stylus -*Supported extensions: `stylus`* +_Supported extensions: `stylus`_ diff --git a/src/i18n/en/docs/toml.md b/src/i18n/en/docs/toml.md index 5750be02f..0c30fd8b2 100644 --- a/src/i18n/en/docs/toml.md +++ b/src/i18n/en/docs/toml.md @@ -1,3 +1,3 @@ # TOML -*Supported extensions: `toml`* +_Supported extensions: `toml`_ diff --git a/src/i18n/en/docs/transforms.md b/src/i18n/en/docs/transforms.md index f3e85b2f6..3a7e22637 100644 --- a/src/i18n/en/docs/transforms.md +++ b/src/i18n/en/docs/transforms.md @@ -2,4 +2,4 @@ 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. -This even works in third-party `node_modules`: if a configuration file is published as part of the package, the transform is automatically turned on for that module only. This keeps bundling fast since only modules that need to be transformed are processed. It also means that you don't need to manually configure the transforms to include and exclude certain files, or know how third party code is built in order to use it in your application. \ No newline at end of file +This even works in third-party `node_modules`: if a configuration file is published as part of the package, the transform is automatically turned on for that module only. This keeps bundling fast since only modules that need to be transformed are processed. It also means that you don't need to manually configure the transforms to include and exclude certain files, or know how third party code is built in order to use it in your application. diff --git a/src/i18n/en/docs/typeScript.md b/src/i18n/en/docs/typeScript.md index 469e7af33..646ed0907 100644 --- a/src/i18n/en/docs/typeScript.md +++ b/src/i18n/en/docs/typeScript.md @@ -1,6 +1,6 @@ # TypeScript -*Supported extensions: `ts`, `tsx`* +_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. @@ -15,11 +15,11 @@ ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` diff --git a/src/i18n/en/docs/vue.md b/src/i18n/en/docs/vue.md index 3faec90a4..38a12ae23 100644 --- a/src/i18n/en/docs/vue.md +++ b/src/i18n/en/docs/vue.md @@ -1,3 +1,3 @@ # Vue -*Supported extensions: `vue`* +_Supported extensions: `vue`_ diff --git a/src/i18n/en/docs/webAssembly.md b/src/i18n/en/docs/webAssembly.md index 38ee66b2b..1e81a002a 100644 --- a/src/i18n/en/docs/webAssembly.md +++ b/src/i18n/en/docs/webAssembly.md @@ -1,6 +1,6 @@ # WebAssembly -*Supported extensions: `wasm`* +_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. @@ -10,11 +10,11 @@ Parcel makes it **extremely easy** to get started with WebAssembly. Assuming you ```js // synchronous import -import {add} from './add.wasm'; -console.log(add(2, 3)); +import { add } from './add.wasm' +console.log(add(2, 3)) // asynchronous import -const {add} = await import('./add.wasm'); -console.log(add(2, 3)); +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. diff --git a/src/i18n/en/docs/webManifest.md b/src/i18n/en/docs/webManifest.md index dcb6e9d01..e787b7547 100644 --- a/src/i18n/en/docs/webManifest.md +++ b/src/i18n/en/docs/webManifest.md @@ -1,3 +1,3 @@ # WebManifest -*Supported extensions: `webmanifest`* +_Supported extensions: `webmanifest`_ diff --git a/src/i18n/en/docs/yaml.md b/src/i18n/en/docs/yaml.md index 536d4bc9b..da83b6df8 100644 --- a/src/i18n/en/docs/yaml.md +++ b/src/i18n/en/docs/yaml.md @@ -1,3 +1,3 @@ # YAML -*Supported extensions: `yaml`, `yml`* +_Supported extensions: `yaml`, `yml`_ diff --git a/src/i18n/es/docs/asset_types.md b/src/i18n/es/docs/asset_types.md index 789d941f5..a0c06d7f7 100644 --- a/src/i18n/es/docs/asset_types.md +++ b/src/i18n/es/docs/asset_types.md @@ -7,14 +7,14 @@ Debido a que Parcel procesa los recursos en paralelo en múltiples núcleos de p ## Interfaz de Recursos ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // establecer el tipo de salida principal + type = 'foo' // establecer el tipo de salida principal parse(code) { // convertir el codigo a un AST - return ast; + return ast } pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // analizar dependencias - this.addDependency('my-dep'); + this.addDependency('my-dep') } transform() { @@ -36,7 +36,7 @@ class MyAsset extends Asset { return { foo: 'my stuff here', // salida principal js: 'some javascript' // representación alternativa para ser colocada en el paquete de JS si es necesario. - }; + } } } ``` @@ -46,8 +46,8 @@ class MyAsset extends Asset { 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/es/docs/assets.md b/src/i18n/es/docs/assets.md index f7bb1ca3c..e7745076c 100644 --- a/src/i18n/es/docs/assets.md +++ b/src/i18n/es/docs/assets.md @@ -8,40 +8,40 @@ El tipo de archivo más común en los empaquetadores web es JavaScript. Parcel s ```javascript // importa un módulo utilizando CommonJS -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // importa un módulo utilizando ES6 -import dep from './path/to/dep'; +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'; +import './test.css' // Importa un archivo CSS con CSS modules -import classNames from './test.css'; +import classNames from './test.css' // Importa la URL de una imagen -import imageURL from './test.png'; +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'; +import fs from 'fs' // Lee el contenido como un string -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Lee el contenido como un Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +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. +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 */ @@ -56,14 +56,19 @@ Los archivos CSS pueden ser importados a partir de un archivo JavaScript o HTML, 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 diff --git a/src/i18n/es/docs/code_splitting.md b/src/i18n/es/docs/code_splitting.md index a8aa183fe..984076223 100644 --- a/src/i18n/es/docs/code_splitting.md +++ b/src/i18n/es/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // Renderiza la página } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Renderiza la página - page.render(); -}); + 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'); +const page = await import('./pages/about') // Renderiza la página -page.render(); +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. @@ -35,12 +36,12 @@ Las importaciones dinámicas también se cargan de forma diferida en Parcel, por 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(); + const page = await pages[name] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +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). diff --git a/src/i18n/es/docs/getting_started.md b/src/i18n/es/docs/getting_started.md index 59baeb652..ea790c1fc 100644 --- a/src/i18n/es/docs/getting_started.md +++ b/src/i18n/es/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel es un empaquetador de aplicaciones web, que se diferencia por la experien Primero instala Parcel utilizando Yarn or npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Crea un archivo package.json en el directorio de su proyecto, usando: ```bash yarn init -y ``` + o + ```bash npm init -y ``` @@ -37,7 +41,7 @@ A continuación, crea los archivos index.html y index.js. ``` ```javascript -console.log("hola mundo"); +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: diff --git a/src/i18n/es/docs/hmr.md b/src/i18n/es/docs/hmr.md index 8d0e8cd5e..40bae8571 100644 --- a/src/i18n/es/docs/hmr.md +++ b/src/i18n/es/docs/hmr.md @@ -8,12 +8,12 @@ Hay dos métodos que se deben conocer: `module.hot.accept` y `module.hot.dispose ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // El módulo está a punto de ser reemplazado - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // El módulo o alguna de sus dependencias ya fueron actualizadas. - }); + }) } ``` diff --git a/src/i18n/es/docs/meta.json b/src/i18n/es/docs/meta.json index 8397e5e84..40d2ec184 100644 --- a/src/i18n/es/docs/meta.json +++ b/src/i18n/es/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "es" } -} \ No newline at end of file +} diff --git a/src/i18n/es/docs/packagers.md b/src/i18n/es/docs/packagers.md index ab8938407..97cf78e3f 100644 --- a/src/i18n/es/docs/packagers.md +++ b/src/i18n/es/docs/packagers.md @@ -5,22 +5,22 @@ En Parcel, un `Packager` combina multiples `Asset`s en un paquete de salida fina ## Interfaz de Packager ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // opcional. escribir cabeceras de archivo si es necesario. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // requerido. escribir el recurso al archivo de salida. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // opcional. escribir el trailer del archivo si es necesario. - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MyPackager extends 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/es/docs/plugins.md b/src/i18n/es/docs/plugins.md index 2794220dd..4c02b2c9e 100644 --- a/src/i18n/es/docs/plugins.md +++ b/src/i18n/es/docs/plugins.md @@ -2,17 +2,17 @@ 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. +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')); -}; +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. diff --git a/src/i18n/es/docs/transforms.md b/src/i18n/es/docs/transforms.md index 6f89282ca..77cabd656 100644 --- a/src/i18n/es/docs/transforms.md +++ b/src/i18n/es/docs/transforms.md @@ -92,12 +92,14 @@ Los plugins deben ser declarados en el objeto `plugins` como llaves, y las opcio ``` + ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` + ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` diff --git a/src/i18n/fr/docs/api.md b/src/i18n/fr/docs/api.md index 2552df4e7..2f19c897d 100644 --- a/src/i18n/fr/docs/api.md +++ b/src/i18n/fr/docs/api.md @@ -4,6 +4,7 @@ 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'); @@ -55,7 +56,8 @@ runBundle(); 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 **pour la première fois**. L'instance du [bundle](#bundle) principal est passé à la fonction de rappel +- `bundled` est appelé une seule fois lorsque Parcel a terminé avec succès l'empaquetage **pour la première fois**. L'instance du [bundle](#bundle) principal est passé à la fonction de rappel + ```Javascript const bundler = new Bundler(...); bundler.on('bundled', (bundle) => { @@ -65,7 +67,8 @@ bundler.on('bundled', (bundle) => { 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 +- `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', () => { @@ -75,7 +78,8 @@ bundler.on('buildEnd', () => { bundler.bundle(); ``` -* `buildStart` est appelé au début de la première construction, le tableau `entryFiles` est passé à la fonction de rappel +- `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 => { @@ -85,7 +89,8 @@ bundler.on('buildStart', entryPoints => { bundler.bundle(); ``` -* `buildError` est appelé chaque fois qu'une erreur se produit pendant les constructions, l'objet `Error` est passé à la fonction de rappel +- `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 => { @@ -101,21 +106,20 @@ Un paquet (`Bundle`) est ce que Parcel utilise pour regrouper les ressources ens #### 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` de tous les paquets frères -* `offsets`: Un `Map` de tous les emplacements des ressources à l'intérieur, utilisé pour générer des sourcemaps précises +- `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` de tous les paquets frères +- `offsets`: Un `Map` 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 : @@ -158,6 +162,7 @@ index.html 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')(); diff --git a/src/i18n/fr/docs/asset_types.md b/src/i18n/fr/docs/asset_types.md index 5011989fe..be1eeda84 100644 --- a/src/i18n/fr/docs/asset_types.md +++ b/src/i18n/fr/docs/asset_types.md @@ -60,8 +60,8 @@ module.exports = MyAsset 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MonAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MonAsset')) ``` diff --git a/src/i18n/fr/docs/cli.md b/src/i18n/fr/docs/cli.md index f21ef5cc2..d6f3b6ba8 100644 --- a/src/i18n/fr/docs/cli.md +++ b/src/i18n/fr/docs/cli.md @@ -138,7 +138,7 @@ parcel entry.js --log-level 1 ``` | Loglevel | Effet | -|--- |--- | +| -------- | ------------------------------------------- | | 0 | Journal désactivé | | 1 | Consigner uniquement les erreurs | | 2 | Consigner les erreurs et les avertissements | diff --git a/src/i18n/fr/docs/code_splitting.md b/src/i18n/fr/docs/code_splitting.md index df038f36b..d1cbd5fde 100644 --- a/src/i18n/fr/docs/code_splitting.md +++ b/src/i18n/fr/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // Donne le rendu de la page } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Donne le rendu de la page - page.render(); -}); + page.render() +}) ``` 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'); +const page = await import('./pages/about') // Donne le rendu de la page -page.render(); +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. @@ -35,12 +36,12 @@ Les importations dynamiques sont également chargées à la volée dans Parcel, 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(); + const page = await pages[name] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +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). diff --git a/src/i18n/fr/docs/coffeeScript.md b/src/i18n/fr/docs/coffeeScript.md index bc25ad26b..e067fc7f2 100644 --- a/src/i18n/fr/docs/coffeeScript.md +++ b/src/i18n/fr/docs/coffeeScript.md @@ -1,3 +1,3 @@ # CoffeeScript -*Extensions supportées : `coffee`* +_Extensions supportées : `coffee`_ diff --git a/src/i18n/fr/docs/css.md b/src/i18n/fr/docs/css.md index 68664e33a..3221451ba 100644 --- a/src/i18n/fr/docs/css.md +++ b/src/i18n/fr/docs/css.md @@ -1,6 +1,6 @@ # CSS -*Extensions supportées : `css`, `pcss`, `postcss`* +_Extensions supportées : `css`, `pcss`, `postcss`_ Les ressources CSS peuvent être importées à partir d'un fichier JavaScript ou HTML et elles 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. @@ -60,11 +60,14 @@ Parcel ajoute [cssnano](http://cssnano.co) à postcss afin de minifier le css po ```js module.exports = { - preset: ['default', { - calc: false, - discardComments: { - removeAll: true, + preset: [ + 'default', + { + calc: false, + discardComments: { + removeAll: true + } } - }] -}; + ] +} ``` diff --git a/src/i18n/fr/docs/getting_started.md b/src/i18n/fr/docs/getting_started.md index 99d7eed76..7de75ef8a 100644 --- a/src/i18n/fr/docs/getting_started.md +++ b/src/i18n/fr/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel est un empaqueteur d'application web, qui se différencie par son expéri Commencez par installer Parcel en utilisant Yarn ou npm : Yarn : + ```bash yarn global add parcel-bundler ``` npm : + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Créez un fichier package.json dans le répertoire de votre projet en utilisant ```bash yarn init -y ``` + ou + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Ensuite, créez un fichier index.html et index.js. ``` ```javascript -console.log("hello world"); +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. Il suffit de le faire pointer sur votre fichier d'entrée : @@ -59,16 +63,19 @@ parcel watch index.html 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 : +_REMARQUE :_ Si vous avez une structure de fichier comme celle-ci : + ``` - répertoire-1 -- index.html @@ -111,8 +118,7 @@ Ajoutez ensuite ces scripts de tâches à votre projet, en modifiant votre `pack Ensuite, vous pourrez les exécuter: -``` bash - +```bash # Pour exécuter en mode développment yarn dev #ou @@ -122,5 +128,4 @@ npm run dev yarn build #ou npm run build - ``` diff --git a/src/i18n/fr/docs/graphQL.md b/src/i18n/fr/docs/graphQL.md index cfcc743bb..34206fca5 100644 --- a/src/i18n/fr/docs/graphQL.md +++ b/src/i18n/fr/docs/graphQL.md @@ -1,3 +1,3 @@ # GraphQL -*Extensions supportées : `gql`, `graphql`* +_Extensions supportées : `gql`, `graphql`_ diff --git a/src/i18n/fr/docs/hmr.md b/src/i18n/fr/docs/hmr.md index 7fffa9dba..10e6bab4e 100644 --- a/src/i18n/fr/docs/hmr.md +++ b/src/i18n/fr/docs/hmr.md @@ -8,13 +8,13 @@ Il y a deux méthodes à connaître : `module.hot.accept` et `module.hot.dispose ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // le module est sur le point d'être remplacé - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // le module ou l'une de ses dépendances vient d'être mis à jour - }); + }) } ``` @@ -22,16 +22,17 @@ if (module.hot) { 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. +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-linstallation-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. +- `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. diff --git a/src/i18n/fr/docs/html.md b/src/i18n/fr/docs/html.md index 810528a4a..b5f2e8c69 100644 --- a/src/i18n/fr/docs/html.md +++ b/src/i18n/fr/docs/html.md @@ -1,6 +1,6 @@ # HTML -*Extensions supportées : `htm`, `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. @@ -19,6 +19,7 @@ Une ressource HTML est souvent le fichier d'entrée que vous fournissez à Parce ``` ## Importation de ressources non compilés + 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 diff --git a/src/i18n/fr/docs/javascript.md b/src/i18n/fr/docs/javascript.md index 3038bf284..8de97f6ec 100644 --- a/src/i18n/fr/docs/javascript.md +++ b/src/i18n/fr/docs/javascript.md @@ -1,28 +1,28 @@ # Javascript -*Extensions supportées : `js`, `jsx`, `es6`, `jsm`, `mjs`* +_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). ```javascript // Importe un module en utilisant la syntaxe CommonJS -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // Importe un module ES6 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` 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'; +import './test.css' // Importe un fichier CSS avec Modules CSS -import classNames from './test.css'; +import classNames from './test.css' // Importe l'URL d'un fichier image -import imageURL from './test.png'; +import imageURL from './test.png' // Importe un fichier HTML import('./some.html') @@ -35,16 +35,16 @@ require('./some.html') Si vous souhaitez insérer un fichier dans le bundle 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'; +import fs from 'fs' // Lit le contenu comme un String -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Lit le contenu comme un Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') // Convertit le contenu du buffer en image - +; ``` # Babel @@ -61,9 +61,7 @@ Ensuite, créez un `.babelrc`: ```json { - "presets": [ - "@babel/preset-react" - ] + "presets": ["@babel/preset-react"] } ``` @@ -75,4 +73,4 @@ Pour la cible `browser`, il utilise [browserslist](https://github.com/browsersli 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*. +Pour la cible `node`, Parcel utilise le `engines.node` défini dans `package.json`, la valeur par défaut est _node 8_. diff --git a/src/i18n/fr/docs/json.md b/src/i18n/fr/docs/json.md index df499de93..c375388b9 100644 --- a/src/i18n/fr/docs/json.md +++ b/src/i18n/fr/docs/json.md @@ -1,3 +1,3 @@ # JSON -*Extensions supportées : `json`, `json5`* +_Extensions supportées : `json`, `json5`_ diff --git a/src/i18n/fr/docs/less.md b/src/i18n/fr/docs/less.md index e872fbdf8..83fa19b30 100644 --- a/src/i18n/fr/docs/less.md +++ b/src/i18n/fr/docs/less.md @@ -1,3 +1,3 @@ # LESS -*Extensions supportées : `less`* +_Extensions supportées : `less`_ diff --git a/src/i18n/fr/docs/meta.json b/src/i18n/fr/docs/meta.json index 08d51e9af..2a190ab3e 100644 --- a/src/i18n/fr/docs/meta.json +++ b/src/i18n/fr/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "fr" } -} \ No newline at end of file +} diff --git a/src/i18n/fr/docs/module_resolution.md b/src/i18n/fr/docs/module_resolution.md index 95868ff1d..42a0bc0c8 100644 --- a/src/i18n/fr/docs/module_resolution.md +++ b/src/i18n/fr/docs/module_resolution.md @@ -63,7 +63,7 @@ et réexporter l'export nommé dans le fichier aliasé : ```js // electron-ipc.js -module.exports = require("electron").ipcRenderer; +module.exports = require('electron').ipcRenderer ``` ### Résolution TypeScript ~ @@ -84,7 +84,7 @@ TypeScript devra connaître votre utilisation de la résolution de module `~` ou ### Résolution Monorepo -Ce sont en ce moment les utilisations conseillées avec des monorepos : +Ce sont en ce moment les utilisations conseillées avec des monorepos : Utilisation conseillée : diff --git a/src/i18n/fr/docs/openGL.md b/src/i18n/fr/docs/openGL.md index 0c238c99b..cd16e8b33 100644 --- a/src/i18n/fr/docs/openGL.md +++ b/src/i18n/fr/docs/openGL.md @@ -1,3 +1,3 @@ # OpenGL Shading Language (GLSL) -*Extensions supportées : `glsl`, `vert`, `frag`* +_Extensions supportées : `glsl`, `vert`, `frag`_ diff --git a/src/i18n/fr/docs/packagers.md b/src/i18n/fr/docs/packagers.md index 6cfbb4d22..450e01ca7 100644 --- a/src/i18n/fr/docs/packagers.md +++ b/src/i18n/fr/docs/packagers.md @@ -5,22 +5,22 @@ Dans Parcel, un `Packager` combine plusieurs `Asset` ensemble dans un paquet fin ## Packager Interface ```javascript -const {Packager} = require('parcel-bundler'); +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); + await this.dest.write(header) } async addAsset(asset) { // obligatoire. Ecrit la ressource dans le fichier de sortie. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // optionnel. Ecrit la fin du fichier si besoin. - await this.dest.end(trailer); + await this.dest.end(trailer) } } @@ -32,8 +32,8 @@ module.exports = MyPackager Vous pouvez enregistrer votre packager avec un 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MonPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MonPackager')) ``` diff --git a/src/i18n/fr/docs/plugins.md b/src/i18n/fr/docs/plugins.md index 777293725..f976c8a54 100644 --- a/src/i18n/fr/docs/plugins.md +++ b/src/i18n/fr/docs/plugins.md @@ -9,10 +9,10 @@ Lors de l'ajout du support pour un nouveau format de fichier à Parcel, vous dev 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')); -}; +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. diff --git a/src/i18n/fr/docs/production.md b/src/i18n/fr/docs/production.md index 514e63ff6..fb772e59d 100644 --- a/src/i18n/fr/docs/production.md +++ b/src/i18n/fr/docs/production.md @@ -18,15 +18,15 @@ Pour permettre à votre cdn de définir des règles de mise en cache très agres Parcel suit le tableau suivant, lorsqu’il s’agit de nommer des bundles. (Les points d'entrée ne sont jamais hachés) -| Type de bundle | Type | Contenu haché | -| ---:| --- |:---:|:---:| -| Tous | point d'entrée | ❌ | -| JavaScript | ` diff --git a/src/i18n/fr/docs/rust.md b/src/i18n/fr/docs/rust.md index 122772c4c..e288826fc 100644 --- a/src/i18n/fr/docs/rust.md +++ b/src/i18n/fr/docs/rust.md @@ -1,6 +1,6 @@ # Rust -*Extensions supportées : `rs`* +_Extensions supportées : `rs`_ [Rust](https://www.rust-lang.org/fr-FR/) 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 ! @@ -10,11 +10,11 @@ Comme avec les fichiers `.wasm`, les fichiers `.rs` peuvent être importés avec ```js // import synchrone -import {add} from './add.rs'; -console.log(add(2, 3)); +import { add } from './add.rs' +console.log(add(2, 3)) // import asynchrone -const {add} = await import('./add.rs'); -console.log(add(2, 3)); +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. diff --git a/src/i18n/fr/docs/scss.md b/src/i18n/fr/docs/scss.md index d0d058650..23292aa61 100644 --- a/src/i18n/fr/docs/scss.md +++ b/src/i18n/fr/docs/scss.md @@ -1,13 +1,17 @@ # SCSS -*Extensions supportées : `sass`, `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 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`. diff --git a/src/i18n/fr/docs/stylus.md b/src/i18n/fr/docs/stylus.md index a14fcd960..05e24b496 100644 --- a/src/i18n/fr/docs/stylus.md +++ b/src/i18n/fr/docs/stylus.md @@ -1,3 +1,3 @@ # Stylus -*Extensions supportées : `stylus`* +_Extensions supportées : `stylus`_ diff --git a/src/i18n/fr/docs/toml.md b/src/i18n/fr/docs/toml.md index abecaa927..1f7c9506c 100644 --- a/src/i18n/fr/docs/toml.md +++ b/src/i18n/fr/docs/toml.md @@ -1,3 +1,3 @@ # TOML -*Extensions supportées : `toml`* +_Extensions supportées : `toml`_ diff --git a/src/i18n/fr/docs/typeScript.md b/src/i18n/fr/docs/typeScript.md index e91fb8c49..02fd23d4f 100644 --- a/src/i18n/fr/docs/typeScript.md +++ b/src/i18n/fr/docs/typeScript.md @@ -1,6 +1,6 @@ # TypeScript -*Extensions supportées : `ts`, `tsx`* +_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. @@ -15,11 +15,11 @@ ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` diff --git a/src/i18n/fr/docs/vue.md b/src/i18n/fr/docs/vue.md index 49e763f06..695f8ec42 100644 --- a/src/i18n/fr/docs/vue.md +++ b/src/i18n/fr/docs/vue.md @@ -1,3 +1,3 @@ # Vue -*Extensions supportées : `vue`* +_Extensions supportées : `vue`_ diff --git a/src/i18n/fr/docs/webAssembly.md b/src/i18n/fr/docs/webAssembly.md index a0382c28d..2a62feb9c 100644 --- a/src/i18n/fr/docs/webAssembly.md +++ b/src/i18n/fr/docs/webAssembly.md @@ -1,20 +1,20 @@ # WebAssembly -*Extensions supportées : `wasm`* +_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. +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 { add } from './add.wasm' +console.log(add(2, 3)) // import asynchrone -const {add} = await import('./add.wasm'); -console.log(add(2, 3)); +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. diff --git a/src/i18n/fr/docs/webManifest.md b/src/i18n/fr/docs/webManifest.md index 96ba93e48..54ea957af 100644 --- a/src/i18n/fr/docs/webManifest.md +++ b/src/i18n/fr/docs/webManifest.md @@ -1,3 +1,3 @@ # WebManifest -*Extensions supportées : `webmanifest`* +_Extensions supportées : `webmanifest`_ diff --git a/src/i18n/fr/docs/yaml.md b/src/i18n/fr/docs/yaml.md index 8b06b89fd..67e1a1f60 100644 --- a/src/i18n/fr/docs/yaml.md +++ b/src/i18n/fr/docs/yaml.md @@ -1,3 +1,3 @@ # YAML -*Extensions supportées : `yaml`, `yml`* +_Extensions supportées : `yaml`, `yml`_ diff --git a/src/i18n/it/docs/api.md b/src/i18n/it/docs/api.md index 6786216db..3e29cbfb8 100644 --- a/src/i18n/it/docs/api.md +++ b/src/i18n/it/docs/api.md @@ -5,6 +5,7 @@ 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'); @@ -42,7 +43,8 @@ const bundle = await bundler.bundle(); 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 +- `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) => { @@ -50,7 +52,8 @@ bundler.on('bundled', (bundler) => { }); ``` -* `buildEnd` viene chiamato dopo ogni compilazione, restituendo un alert anche se si è verificato un errore +- `buildEnd` viene chiamato dopo ogni compilazione, restituendo un alert anche se si è verificato un errore + ```Javascript const bundler = new Bundler(...); bundler.on('buildEnd', () => { @@ -64,15 +67,15 @@ Un "bundle" è ciò che Parcel usa per raggruppare le risorse, questo contiene a #### 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` di tutti i bundle figli -* `offsets`: Un `Map` di tutte le posizioni degli assets nel bundle, usato per generare sourcemaps accurate. +- `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` di tutti i bundle figli +- `offsets`: Un `Map` di tutte le posizioni degli assets nel bundle, usato per generare sourcemaps accurate. #### Tree @@ -120,6 +123,7 @@ index.html 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')(); diff --git a/src/i18n/it/docs/asset_types.md b/src/i18n/it/docs/asset_types.md index 97d01c0b7..cef8b4090 100644 --- a/src/i18n/it/docs/asset_types.md +++ b/src/i18n/it/docs/asset_types.md @@ -7,14 +7,14 @@ Parcel elabora le risorse in parallelo su più core di elaborazione e le trasfor ## Interfaccia degli Asset ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // imposta il tipo principale di output. + type = 'foo' // imposta il tipo principale di output. async parse(code) { // Parsing del codice su un AST - return ast; + return ast } async pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // analizza le dipendenze - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { @@ -43,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', // esecuzione alternativa, da collocare in un bundle JS se necessario sourceMap } - ]; + ] } async postProcess(generated) { @@ -58,8 +58,8 @@ class MyAsset extends 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MioAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MioAsset')) ``` diff --git a/src/i18n/it/docs/assets.md b/src/i18n/it/docs/assets.md index 16a4db3cc..1c2627946 100644 --- a/src/i18n/it/docs/assets.md +++ b/src/i18n/it/docs/assets.md @@ -8,35 +8,35 @@ Il tipo di file più tradizionale per i web bundlers é JavaScript. Parcel suppo ```javascript // Importa un modulo utilizzando la sintassi CommonJS -const dep = require('./percorso/al/file'); +const dep = require('./percorso/al/file') // Importa un modulo utilizzando la sintassi ES6 -import dep from './percorso/al/file'; +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'; +import './test.css' // Importa un file CSS utilizzando CSS Modules -import classNames from './test.css'; +import classNames from './test.css' // Importa un'immagine da un URL -import imageURL from './test.png'; +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'; +import fs from 'fs' // Legge i contenuti come una stringa -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Legge i contenuti come un Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') ``` ## CSS @@ -56,14 +56,19 @@ Gli assets CSS possono essere importati da un file JavaScript o da un file HTML, 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 diff --git a/src/i18n/it/docs/cli.md b/src/i18n/it/docs/cli.md index 8cf07d230..684cb03bf 100644 --- a/src/i18n/it/docs/cli.md +++ b/src/i18n/it/docs/cli.md @@ -95,12 +95,12 @@ Disponibile in: `serve`, `watch`, `build` 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 | +| Loglevel | Effetto | +| -------- | ------------------- | +| 0 | Logging disattivo | +| 1 | Log solo errori | +| 2 | Log errori e avvisi | +| 3 | Log di tutto | ### HMR Hostname @@ -212,4 +212,4 @@ Disponibile in: `serve`, `watch`, `build` ```bash parcel build entry.js --no-cache -``` \ No newline at end of file +``` diff --git a/src/i18n/it/docs/code_splitting.md b/src/i18n/it/docs/code_splitting.md index c5bd311fd..cac02a8c2 100644 --- a/src/i18n/it/docs/code_splitting.md +++ b/src/i18n/it/docs/code_splitting.md @@ -1,4 +1,5 @@ # ✂️ 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. @@ -11,19 +12,20 @@ export function render() { // Render della pagina } ``` + ```javascript -import('./pagine/info').then(function (page) { +import('./pagine/info').then(function(page) { // Render della pagina - page.render(); -}); + 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'); +const page = await import('./pages/about') // Render della pagina -page.render(); +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. @@ -34,12 +36,12 @@ Anche le importazioni dinamiche sono gestite in lazy loading in Parcel, così pu 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(); + const page = await pages[name] + return page.render() } ``` @@ -50,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +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). diff --git a/src/i18n/it/docs/getting_started.md b/src/i18n/it/docs/getting_started.md index 1938c9ebc..d530b80cd 100644 --- a/src/i18n/it/docs/getting_started.md +++ b/src/i18n/it/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel è un bundle di applicazioni web, che si differenzia per la sua developer Per prima cosa installa Parcel usando Yarn o npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Creare un file package.json nella cartella del progetto: ```bash yarn init -y ``` -or + +or + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Successivamente, creare un file index.html e index.js. ``` ```javascript -console.log("hello world"); +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: @@ -54,4 +58,4 @@ Usa il server di sviluppo quando non hai un tuo server, o la tua applicazione è 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. \ No newline at end of file +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. diff --git a/src/i18n/it/docs/hmr.md b/src/i18n/it/docs/hmr.md index 24fd791b1..7177e7c29 100644 --- a/src/i18n/it/docs/hmr.md +++ b/src/i18n/it/docs/hmr.md @@ -8,22 +8,23 @@ Ci sono due metodi da conoscere: `module.hot.accept` e `module.hot.dispose`. Si ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // il modulo sta per essere sostituito - }); + }) - module.hot.accept(function () { + 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. +- `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. diff --git a/src/i18n/it/docs/how_it_works.md b/src/i18n/it/docs/how_it_works.md index 43be574ea..6e7a14c6c 100644 --- a/src/i18n/it/docs/how_it_works.md +++ b/src/i18n/it/docs/how_it_works.md @@ -16,4 +16,4 @@ Se una risorsa è richiesta in più di un bundle, viene spostata fino all'antena ### 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. \ No newline at end of file +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. diff --git a/src/i18n/it/docs/meta.json b/src/i18n/it/docs/meta.json index 7d0908a1e..49dc504f5 100644 --- a/src/i18n/it/docs/meta.json +++ b/src/i18n/it/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "it" } -} \ No newline at end of file +} diff --git a/src/i18n/it/docs/packagers.md b/src/i18n/it/docs/packagers.md index c67cf3f5d..9f989da6c 100644 --- a/src/i18n/it/docs/packagers.md +++ b/src/i18n/it/docs/packagers.md @@ -5,22 +5,22 @@ In Parcel, un `Packager` combina multipli `Assets` insieme in un bundle di outpu ## Interfaccia del Packager ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MioPackager extends Packager { async start() { // facoltativo. scrive il file header se richiesto. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // obbligatorio. scrive l'asset nel file output - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // facoltativo. scrive il file trailer se richiesto. - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MioPackager extends 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'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MioPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MioPackager')) ``` diff --git a/src/i18n/it/docs/plugins.md b/src/i18n/it/docs/plugins.md index fa4e8003e..4c4e3a92c 100644 --- a/src/i18n/it/docs/plugins.md +++ b/src/i18n/it/docs/plugins.md @@ -1,4 +1,5 @@ # 🔌 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. @@ -8,10 +9,10 @@ Quando si aggiunge il supporto per un nuovo formato di file a Parcel, si dovrebb 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')); -}; +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. diff --git a/src/i18n/it/docs/production.md b/src/i18n/it/docs/production.md index 67cd6e359..20e338f8e 100644 --- a/src/i18n/it/docs/production.md +++ b/src/i18n/it/docs/production.md @@ -5,6 +5,7 @@ Quando si tratta di preparare l'applicazione per il server di Produzione, è pos ```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. \ No newline at end of file +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. diff --git a/src/i18n/it/docs/transforms.md b/src/i18n/it/docs/transforms.md index e7caad2df..98442a73e 100644 --- a/src/i18n/it/docs/transforms.md +++ b/src/i18n/it/docs/transforms.md @@ -99,13 +99,13 @@ I Plugins sono specificati nell'oggetto `plugins` come chiavi, e le opzioni sono ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Ciao, Mondo"; +export default 'Ciao, Mondo' ``` ## ReasonML/BuckleScript @@ -131,8 +131,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, @@ -211,7 +210,7 @@ $ yarn add react react-dom reason-react ``` ```reason -/* src/Greeting.re */ +/* src/Greeting.re */ let component = ReasonReact.statelessComponent("Saluta"); diff --git a/src/i18n/ko/docs/api.md b/src/i18n/ko/docs/api.md index 078ca1f78..18d06b2b3 100644 --- a/src/i18n/ko/docs/api.md +++ b/src/i18n/ko/docs/api.md @@ -2,14 +2,15 @@ ## 번들러 -보다 복잡한 사용을 위해(가령 매 빌드 후 임의의 프로세싱을 해야한다던가) CLI 대신 API를 이용해서 번들러를 초기화 할 수 있습니다. +보다 복잡한 사용을 위해(가령 매 빌드 후 임의의 프로세싱을 해야한다던가) CLI 대신 API 를 이용해서 번들러를 초기화 할 수 있습니다. 모든 옵션이 설명된 아래 예시를 보세요. + ```js -const Bundler = require('parcel-bundler'); -const Path = require('path'); +const Bundler = require('parcel-bundler') +const Path = require('path') // 진입점 파일 위치 -const file = Path.join(__dirname, './index.html'); +const file = Path.join(__dirname, './index.html') // 번들러 옵션 const options = { @@ -27,25 +28,26 @@ const options = { sourceMaps: true, // 소스맵을 활성화할지 여부. 기본값은 활성화 (아직 미니파이드 빌드에선 지원되지 않음) hmrHostname: '', // 빠른 모듈 교체를 위한 hostname.기본값은 '' detailedReport: false // 번들, 애셋, 파일 크기, 빌드 시간을 담은 상세한 리포트를 출력. 기본값은 false. 리포트는 오직 watch가 비활성일때만 출력됨 -}; +} async function runBundle() { // 진입점 위치와 옵션을 제공해서 번들러를 초기화 - const bundler = new Bundler(file, options); + const bundler = new Bundler(file, options) // 번들러를 실행함. 이것은 메인 번들을 반환함. // watch 모드를 사용할 경우 이 promise는 매 빌드마다 호출하는게 아니라 딱 한 번만 호출하고 이벤트를 사용할 것 - const bundle = await bundler.bundle(); + const bundle = await bundler.bundle() } -runBundle(); +runBundle() ``` ### 이벤트 모든 번들러 이벤트 목록입니다. -* `bundled` 이벤트는 **처음 한 번만**, Parcel이 성공적으로 번들링을 마친 후 발생되어, 메인 [번들](#번들)을 callback에 전달합니다. +- `bundled` 이벤트는 **처음 한 번만**, Parcel 이 성공적으로 번들링을 마친 후 발생되어, 메인 [번들](#번들)을 callback 에 전달합니다. + ```js const bundler = new Bundler(...); bundler.on('bundled', (bundler) => { @@ -54,7 +56,8 @@ bundler.on('bundled', (bundler) => { // 어디선가 bundler.bundle() 를 호출함 ``` -* `buildEnd` 이벤트는 **재빌드를 포함한** 빌드 후 매번 발생됩니다. 에러가 발생한 경우에도 발생합니다. +- `buildEnd` 이벤트는 **재빌드를 포함한** 빌드 후 매번 발생됩니다. 에러가 발생한 경우에도 발생합니다. + ```js const bundler = new Bundler(...); bundler.on('buildEnd', () => { @@ -65,25 +68,24 @@ bundler.on('buildEnd', () => { ### 번들 -`Bundle`은 Parcel이 애셋을 함께 번들링하기 위해 사용하며, 번들 트리를 빌드하기 위해 자식, 형제 번들을 포함합니다. +`Bundle`은 Parcel 이 애셋을 함께 번들링하기 위해 사용하며, 번들 트리를 빌드하기 위해 자식, 형제 번들을 포함합니다. #### 속성들 -* `type`: 애셋의 종류 (e.g. js, css, map, ...) -* `name`: 번들의 이름 (`entryAsset`의 `Asset.generateBundleName()`로 생성) -* `parentBundle`: 부모 번들. 진입점 번들일 경우 null -* `entryAsset`: 번들의 진입점. name의 생성 및 애셋 수집에 사용. -* `assets`: 번들 안에 있는 모든 애셋의 집합(`Set`) -* `childBundles`: 모든 자식 번들의 `Set` -* `siblingBundles`: 모든 형제 번들의 `Set` -* `siblingBundlesMap`: 모든 형제 번들의 `Map` -* `offsets`: 번들 안의 애셋 속의 모든 위치의 `Map`. 정확한 소스맵 생성을 위해 사용됨 +- `type`: 애셋의 종류 (e.g. js, css, map, ...) +- `name`: 번들의 이름 (`entryAsset`의 `Asset.generateBundleName()`로 생성) +- `parentBundle`: 부모 번들. 진입점 번들일 경우 null +- `entryAsset`: 번들의 진입점. name 의 생성 및 애셋 수집에 사용. +- `assets`: 번들 안에 있는 모든 애셋의 집합(`Set`) +- `childBundles`: 모든 자식 번들의 `Set` +- `siblingBundles`: 모든 형제 번들의 `Set` +- `siblingBundlesMap`: 모든 형제 번들의 `Map` +- `offsets`: 번들 안의 애셋 속의 모든 위치의 `Map`. 정확한 소스맵 생성을 위해 사용됨 #### Tree `Bundle`은 `parentBundle`, `childBundles`, `siblingBundles`을 포함하고, 이 모든 속성은 빠르게 번들트리를 순회하여 만들어집니다. - 매우 기본적인 애셋 트리로 번들 트리를 생성합니다. ##### 애셋 트리 @@ -102,7 +104,7 @@ index.html ##### 번들 트리: -`index.html`은 메인 번들을 위해 진입 애셋으로 사용됩니다. 이 메인 번들은 `index.js`과 `index.css` 2개의 자식 번들을 만듭니다. 둘 다 `html`과 다른 타입이기 때문입니다. +`index.html`은 메인 번들을 위해 진입 애셋으로 사용됩니다. 이 메인 번들은 `index.js`과 `index.css` 2 개의 자식 번들을 만듭니다. 둘 다 `html`과 다른 타입이기 때문입니다. `index.js`는 `test.js`, `test.txt` 두 파일을 필요로 합니다. @@ -125,20 +127,21 @@ index.html 미들웨어는 http 서버의 훅으로 사용될 수 있습니다. (예를 들어 `express`나 node `http`). -Parcel 미들웨어를 express와 사용하는 예제입니다. +Parcel 미들웨어를 express 와 사용하는 예제입니다. + ```js -const Bundler = require('parcel-bundler'); -const app = require('express')(); +const Bundler = require('parcel-bundler') +const app = require('express')() -const file = 'index.html'; // 엔트리 포인트로 쓰일 절대경로를 적습니다 -const options = {}; // 가능한 옵션은 API 문서를 참조하세요 +const file = 'index.html' // 엔트리 포인트로 쓰일 절대경로를 적습니다 +const options = {} // 가능한 옵션은 API 문서를 참조하세요 // 파일과 옵션을 사용해 번들러를 초기화합니다 -const bundler = new Bundler(file, options); +const bundler = new Bundler(file, options) // express가 번들러 미들웨어를 사용할 수 있게 합니다. 그러면 express server를 거치는 매 요청을 Parcel이 처리할 것입니다. -app.use(bundler.middleware()); +app.use(bundler.middleware()) // 8080포트로 listen을 시작합니다. -app.listen(8080); +app.listen(8080) ``` diff --git a/src/i18n/ko/docs/asset_types.md b/src/i18n/ko/docs/asset_types.md index 74ec75f91..36aa30f7f 100644 --- a/src/i18n/ko/docs/asset_types.md +++ b/src/i18n/ko/docs/asset_types.md @@ -1,20 +1,20 @@ # 📝 애셋 유형 -[애셋 문서](assets.html)에 기술했던 것처럼, Parcel은 각 입력 파일을 `Asset`이라고 표현합니다. 애셋 유형(type)은 기본 `Asset` 클래스를 상속한 클래스로 표현됩니다. 애셋 유형은 구문 분석(parse), 종속성 분석, 변환과 코드 생성에 필요한 인터페이스를 구현합니다. +[애셋 문서](assets.html)에 기술했던 것처럼, Parcel 은 각 입력 파일을 `Asset`이라고 표현합니다. 애셋 유형(type)은 기본 `Asset` 클래스를 상속한 클래스로 표현됩니다. 애셋 유형은 구문 분석(parse), 종속성 분석, 변환과 코드 생성에 필요한 인터페이스를 구현합니다. -Parcel은 다중 프로세서 코어로 애셋을 병렬 처리 하기 때문에 애셋 유형이 수행할 수 있는 변환은 한번에 하나의 파일 운용만으로 한정 되어 있습니다. 여러 파일 변환을 위해 사용자 정의 [패키저](packagers.html)를 쓸 수 있습니다. +Parcel 은 다중 프로세서 코어로 애셋을 병렬 처리 하기 때문에 애셋 유형이 수행할 수 있는 변환은 한번에 하나의 파일 운용만으로 한정 되어 있습니다. 여러 파일 변환을 위해 사용자 정의 [패키저](packagers.html)를 쓸 수 있습니다. ## 애셋 인터페이스 ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // 주 출력 유형 설정 + type = 'foo' // 주 출력 유형 설정 async parse(code) { // AST에 코드 구문 분석 - return ast; + return ast } async pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // 의존성 분석. - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { @@ -43,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', // 필요하다면 JS 번들에 배치할 대체 표현(rendition) sourceMap } - ]; + ] } async postProcess(generated) { @@ -58,8 +58,8 @@ class MyAsset extends Asset { `addAssetType` 메소드를 사용해 애셋 유형을 번들러에 등록할 수 있습니다. 이것은 등록할 파일 확장자와 애셋 유형 모듈의 경로를 받아들입니다. 실제 객체가 아닌 경로이기 때문에 워커 프로세스로 전달될 수 있습니다. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/ko/docs/assets.md b/src/i18n/ko/docs/assets.md index 86a1cc27c..a911e702c 100644 --- a/src/i18n/ko/docs/assets.md +++ b/src/i18n/ko/docs/assets.md @@ -1,47 +1,47 @@ # 📦 애셋 -Parcel은 애셋(assets)을 기반으로 합니다. 애셋은 어떤 파일로든 표현될 수 있습니다만, Parcel은 JavaScript, CSS, 그리고 HTML 파일과 같은 특정 유형의 애셋을 특별 지원 합니다. Pacel은 이 파일들 안의 참조에서 자동으로 의존성을 분석하고 출력 번들에 포함시킵니다. 비슷한 유형의 애셋들은 같은 출력 번들로 함께 그룹화 합니다. 만약 다른 유형의 애셋을 임포트 했다면 (예를 들면, JS 파일에서 CSS 파일을 임포트 했다면), 자식 번들이 만들어지고 부모 번들에게 참조를 남깁니다. 후속 섹션에서 이에 대해 설명할 것입니다. +Parcel 은 애셋(assets)을 기반으로 합니다. 애셋은 어떤 파일로든 표현될 수 있습니다만, Parcel 은 JavaScript, CSS, 그리고 HTML 파일과 같은 특정 유형의 애셋을 특별 지원 합니다. Pacel 은 이 파일들 안의 참조에서 자동으로 의존성을 분석하고 출력 번들에 포함시킵니다. 비슷한 유형의 애셋들은 같은 출력 번들로 함께 그룹화 합니다. 만약 다른 유형의 애셋을 임포트 했다면 (예를 들면, JS 파일에서 CSS 파일을 임포트 했다면), 자식 번들이 만들어지고 부모 번들에게 참조를 남깁니다. 후속 섹션에서 이에 대해 설명할 것입니다. ## JavaScript -웹 번들러에 있어 JavaScript는 가장 전통적인 파일 유형입니다. 파일 임포팅을 위해 Parcel은 CommonJS와 ES6 모듈 구문을 모두 지원합니다. 또한 비동기적인 모듈 로드를 위해 다이나믹 `import()` 함수 구문을 지원합니다. 이에 대해선 [코드 분할](code_splitting.html)섹션에서 다룰 것입니다. +웹 번들러에 있어 JavaScript 는 가장 전통적인 파일 유형입니다. 파일 임포팅을 위해 Parcel 은 CommonJS 와 ES6 모듈 구문을 모두 지원합니다. 또한 비동기적인 모듈 로드를 위해 다이나믹 `import()` 함수 구문을 지원합니다. 이에 대해선 [코드 분할](code_splitting.html)섹션에서 다룰 것입니다. ```javascript // CommonJS 구문으로 모듈 임포트 -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // ES6 import 구문으로 모듈 임포트 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` -JavaScript 파일에 JavaScript가 아닌 애셋 또한 임포트 할 수 있습니다. CSS나 이미지 파일도 됩니다. 이런 파일들을 임포트 할 때, 다른 번들러들처럼 인라인화 되지 않습니다. 대신, 그 파일의 모든 의존 항목과 함께 별도의 번들(예로 CSS 파일)속에 위치하게 됩니다. [CSS Modules](https://github.com/css-modules/css-modules)을 사용할 시, 추출 된 클래스들은 JavaScript 번들에 위치합니다. 다른 애셋 유형은 출력 파일에 대한 URL을 JavaScript 번들에 내보냅니다. 이로써 그 파일들에 대한 참조를 코드안에 갖고 있게 됩니다. +JavaScript 파일에 JavaScript 가 아닌 애셋 또한 임포트 할 수 있습니다. CSS 나 이미지 파일도 됩니다. 이런 파일들을 임포트 할 때, 다른 번들러들처럼 인라인화 되지 않습니다. 대신, 그 파일의 모든 의존 항목과 함께 별도의 번들(예로 CSS 파일)속에 위치하게 됩니다. [CSS Modules](https://github.com/css-modules/css-modules)을 사용할 시, 추출 된 클래스들은 JavaScript 번들에 위치합니다. 다른 애셋 유형은 출력 파일에 대한 URL 을 JavaScript 번들에 내보냅니다. 이로써 그 파일들에 대한 참조를 코드안에 갖고 있게 됩니다. ```javascript // CSS 파일 임포트 -import './test.css'; +import './test.css' // CSS modules로 CSS 파일 임포트 -import classNames from './test.css'; +import classNames from './test.css' // 이미지 파일의 URL을 임포트 -import imageURL from './test.png'; +import imageURL from './test.png' ``` -만약 파일을 참조 URL이 아닌 인라인으로 JavaScript 번들에 포함시키고 싶다면, Node.js의 `fs.readFileSync` API를 사용하면 됩니다. 이 때 URL은 정적으로 분석 가능해야 합니다. 이 말인 즉, 그 안에 변수를 가질 수 없다는 뜻입니다. (단, `__dirname` 와 `__filename` 는 예외입니다.) +만약 파일을 참조 URL 이 아닌 인라인으로 JavaScript 번들에 포함시키고 싶다면, Node.js 의 `fs.readFileSync` API 를 사용하면 됩니다. 이 때 URL 은 정적으로 분석 가능해야 합니다. 이 말인 즉, 그 안에 변수를 가질 수 없다는 뜻입니다. (단, `__dirname` 와 `__filename` 는 예외입니다.) ```javascript -import fs from 'fs'; +import fs from 'fs' // 내용을 문자열 값으로 읽습니다. -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // 내용을 버퍼로 읽습니다. -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') ``` ## CSS -CSS 애셋은 JavaScript나 HTML 파일로부터 임포트 될 수 있습니다. CSS애셋에는 `@import` 구문을 통해 참조되는 의존성과 `url()` 함수를 통해 참조되는 이미지, 폰트등이 포함될 수 있습니다. `@import`된 다른 CSS 파일은 동일한 CSS 번들에 인라인으로 포함됩니다. `url()`참조는 그것들의 출력 파일 이름으로 재작성 됩니다. 모든 파일 이름은 현재 CSS 파일과 관련 있어야 합니다. +CSS 애셋은 JavaScript 나 HTML 파일로부터 임포트 될 수 있습니다. CSS 애셋에는 `@import` 구문을 통해 참조되는 의존성과 `url()` 함수를 통해 참조되는 이미지, 폰트등이 포함될 수 있습니다. `@import`된 다른 CSS 파일은 동일한 CSS 번들에 인라인으로 포함됩니다. `url()`참조는 그것들의 출력 파일 이름으로 재작성 됩니다. 모든 파일 이름은 현재 CSS 파일과 관련 있어야 합니다. ```css /* 다른 CSS 파일 임포트 */ @@ -57,21 +57,23 @@ CSS 애셋은 JavaScript나 HTML 파일로부터 임포트 될 수 있습니다. ## SCSS -SCSS를 컴파일 하기 위해서는 `sass` 모듈이 필요합니다. 다음 명령어로 설치해주세요. +SCSS 를 컴파일 하기 위해서는 `sass` 모듈이 필요합니다. 다음 명령어로 설치해주세요. + ```bash npm install sass ``` + `sass`를 설치했다면 이제 SCSS 파일을 JavaScript 파일에서 import 할 수 있습니다. + ```javascript import './custom.scss' ``` -SCSS에서 `@import` 구문으로 포함된 의존성도 처리됩니다. - +SCSS 에서 `@import` 구문으로 포함된 의존성도 처리됩니다. ## HTML -HTML 애셋은 주로 Parcel 진입 파일로 사용됩니다. 그렇지만 JavaScript 파일에 의해서, 예로 다른 페이지로의 링크를 제공하기위해 참조 될 수도 있습니다. 스크립트, 스타일, 미디어, 그리고 다른 HTML 파일의 URL은 위에서 설명한것 처럼 추출되고 컴파일됩니다. 참조는 HTML 안에서 재작성 됨으로써 정확한 출력 파일로 연결 됩니다. 모든 파일 이름은 현재의 HTML 파일과 관련 있어야 합니다. +HTML 애셋은 주로 Parcel 진입 파일로 사용됩니다. 그렇지만 JavaScript 파일에 의해서, 예로 다른 페이지로의 링크를 제공하기위해 참조 될 수도 있습니다. 스크립트, 스타일, 미디어, 그리고 다른 HTML 파일의 URL 은 위에서 설명한것 처럼 추출되고 컴파일됩니다. 참조는 HTML 안에서 재작성 됨으로써 정확한 출력 파일로 연결 됩니다. 모든 파일 이름은 현재의 HTML 파일과 관련 있어야 합니다. ```html diff --git a/src/i18n/ko/docs/cli.md b/src/i18n/ko/docs/cli.md index 9e4390c04..71baff640 100644 --- a/src/i18n/ko/docs/cli.md +++ b/src/i18n/ko/docs/cli.md @@ -36,7 +36,7 @@ parcel help ### Version -Parcel의 버전을 출력합니다. +Parcel 의 버전을 출력합니다. ```bash parcel --version @@ -123,12 +123,12 @@ parcel serve entry.js --port 1111 parcel entry.js --log-level 1 ``` -| 로그 레벨 | 효과 | -|--- |--- | -| 0 | 로깅 비활성화 | -| 1 | 에러만 로그 | -| 2 | 에러와 경고를 로그 | -| 3 | 모두 로깅 | +| 로그 레벨 | 효과 | +| --------- | ------------------ | +| 0 | 로깅 비활성화 | +| 1 | 에러만 로그 | +| 2 | 에러와 경고를 로그 | +| 3 | 모두 로깅 | ### 빠른 모듈 교체 호스트네임 @@ -176,13 +176,13 @@ parcel build entry.js --detailed-report 기본값: https 비활성 -같이 사용 가능한 명령어: `serve`, `watch` (HMR 연결을 위해 HTTPS로 수신) +같이 사용 가능한 명령어: `serve`, `watch` (HMR 연결을 위해 HTTPS 로 수신) ```bash parcel entry.js --https ``` -⚠️ 이 옵션은 자가서명된 인증서를 생성하므로 사용을 위해서는 브라우저에서 localhost에 대해 자가서명된 인증서를 허용하도록 설정할 필요가 있습니다. +⚠️ 이 옵션은 자가서명된 인증서를 생성하므로 사용을 위해서는 브라우저에서 localhost 에 대해 자가서명된 인증서를 허용하도록 설정할 필요가 있습니다. ### 임의의 인증서 설정 @@ -254,8 +254,7 @@ parcel build entry.js --no-minify parcel build entry.js --no-cache ``` - -### 모듈을 UMD로 출력 +### 모듈을 UMD 로 출력 기본값: 비활성화 @@ -275,4 +274,4 @@ parcel serve entry.js --global myvariable parcel serve entry.js --experimental-scope-hoisting ``` -더 자세한 정보는 Devon Govett이 Parcel 1.9에 대해 작성한 글의 [Tree Shaking section(영문)](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3)을 참조하세요. +더 자세한 정보는 Devon Govett 이 Parcel 1.9 에 대해 작성한 글의 [Tree Shaking section(영문)](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3)을 참조하세요. diff --git a/src/i18n/ko/docs/code_splitting.md b/src/i18n/ko/docs/code_splitting.md index 6d41b5640..fe8e5fde1 100644 --- a/src/i18n/ko/docs/code_splitting.md +++ b/src/i18n/ko/docs/code_splitting.md @@ -1,27 +1,27 @@ # ✂️ 코드 분할 -Parcel은 일체의 설정 없이(zero configuration) 코드 분할(splitting)을 지원합니다. 애플리케이션 코드를 필요할 때에 로드할 수 있는 각각의 번들로 분할 할 수 있습니다. 이로 인해 초기 번들이 더 작아지고 로드 시간이 더 빨리지게 됩니다. 사용자가 애플리케이션을 탐색하다 모듈이 필요해지면, Parcel이 자동으로 필요한 하위 번들을 처리합니다. +Parcel 은 일체의 설정 없이(zero configuration) 코드 분할(splitting)을 지원합니다. 애플리케이션 코드를 필요할 때에 로드할 수 있는 각각의 번들로 분할 할 수 있습니다. 이로 인해 초기 번들이 더 작아지고 로드 시간이 더 빨리지게 됩니다. 사용자가 애플리케이션을 탐색하다 모듈이 필요해지면, Parcel 이 자동으로 필요한 하위 번들을 처리합니다. 코드 분할은 다이나믹 `import()` 함수 [구문 제안](https://github.com/tc39/proposal-dynamic-import)으로 제어합니다. 이 함수는 보통의 `import`나 `require`함수처럼 움직이지만 프로미스(Promise)를 반환합니다. 이것은 모듈이 비동기적으로 로드됨을 의미합니다. 아래 예제는 다이나믹 임포트로 애플리케이션 요구에 따라 어떻게 서브페이지를 로드하는지 보여줍니다. ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // 페이지 렌더 - page.default(); -}); + page.default() +}) ``` -`import()`가 프로미스를 반환하기 때문에 async/await 구문을 사용할 수 있습니다. 더 많은 브라우저가 이를 지원하기 전 까지는 Babel을 구성하여 구문을 변환할 필요가 있을 겁니다. +`import()`가 프로미스를 반환하기 때문에 async/await 구문을 사용할 수 있습니다. 더 많은 브라우저가 이를 지원하기 전 까지는 Babel 을 구성하여 구문을 변환할 필요가 있을 겁니다. ```javascript -const page = await import('./pages/about'); +const page = await import('./pages/about') // 페이지 렌더 -page.default(); +page.default() ``` -다이나믹 임포트는 Pacel에서 지연 로드 됩니다. 따라서 모든 `import()` 호출을 파일 최상위에 놓고 하위 번들이 사용되기 전까지 로드되지 않게 할 수 있습니다. 아래 예제는 애플리케이션 서브페이지가 동적으로 지연 로드되는 방식을 보여줍니다. +다이나믹 임포트는 Pacel 에서 지연 로드 됩니다. 따라서 모든 `import()` 호출을 파일 최상위에 놓고 하위 번들이 사용되기 전까지 로드되지 않게 할 수 있습니다. 아래 예제는 애플리케이션 서브페이지가 동적으로 지연 로드되는 방식을 보여줍니다. ```javascript // 다이나믹 임포트 할 페이지 이름을 준비. @@ -29,24 +29,24 @@ page.default(); const pages = { about: import('./pages/about'), blog: import('./pages/blog') -}; +} async function renderPage(name) { // 요청 페이지 로드 지연 - const page = await pages[name]; - return page.default(); + const page = await pages[name] + return page.default() } ``` -**주의:** 만약 브라우저에서 async/await를 사용하고 싶다면, `babel-polyfill`을 앱에 포함시키거나 `babel-runtime` + `babel-plugin-transform-runtime`이 라이브러리에 있어야 합니다. 그냥 사용하려고 하지 마세요. +**주의:** 만약 브라우저에서 async/await 를 사용하고 싶다면, `babel-polyfill`을 앱에 포함시키거나 `babel-runtime` + `babel-plugin-transform-runtime`이 라이브러리에 있어야 합니다. 그냥 사용하려고 하지 마세요. ```bash yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +import 'babel-polyfill' +import './app' ``` [babel-polyfill](http://babeljs.io/docs/usage/polyfill)와 [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime)를 읽어보세요. diff --git a/src/i18n/ko/docs/getting_started.md b/src/i18n/ko/docs/getting_started.md index a42da7165..c6f62ffaa 100644 --- a/src/i18n/ko/docs/getting_started.md +++ b/src/i18n/ko/docs/getting_started.md @@ -2,31 +2,35 @@ Parcel`[파설, /parsəl/]`은 개발 경험에서 차이를 느낄수 있는 웹 애플리케이션 번들러 입니다. 멀티코어 프로세싱으로 불꽃 튀게 빠른 성능을 제공하고 그 어떤 설정도 요구하지 않습니다. -먼저 Yarn이나 npm으로 Parcel을 설치하세요. +먼저 Yarn 이나 npm 으로 Parcel 을 설치하세요. Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` -그 다음, package.json파일을 프로젝트 디렉토리에 만드세요. +그 다음, package.json 파일을 프로젝트 디렉토리에 만드세요. ```bash yarn init -y ``` + 또는 + ```bash npm init -y ``` -Parcel은 어떤 유형의 파일이라도 진입점으로 취할 수 있지만 HTML이나 JavaScript 파일이 좋습니다. 만약 HTML 파일 내에 상대경로로 메인 JavaScript 파일을 연결 했다면, Parcel은 이 또한 처리 할 것이고, 출력 파일로의 URL 참조를 교체할 겁니다. +Parcel 은 어떤 유형의 파일이라도 진입점으로 취할 수 있지만 HTML 이나 JavaScript 파일이 좋습니다. 만약 HTML 파일 내에 상대경로로 메인 JavaScript 파일을 연결 했다면, Parcel 은 이 또한 처리 할 것이고, 출력 파일로의 URL 참조를 교체할 겁니다. -그럼, index.html과 index.js파일을 만들어 봅시다. +그럼, index.html 과 index.js 파일을 만들어 봅시다. ```html @@ -37,10 +41,10 @@ Parcel은 어떤 유형의 파일이라도 진입점으로 취할 수 있지만 ``` ```javascript -console.log("hello world"); +console.log('hello world') ``` -Parcel은 파일 변화를 자동으로 다시 빌드(rebuild) 하고 [빠른 모듈 교체](hmr.html)를 지원하는 내장 개발용 서버가 있어 빠른 개발이 가능해 집니다. 그저 진입 파일을 지정하면 됩니다: +Parcel 은 파일 변화를 자동으로 다시 빌드(rebuild) 하고 [빠른 모듈 교체](hmr.html)를 지원하는 내장 개발용 서버가 있어 빠른 개발이 가능해 집니다. 그저 진입 파일을 지정하면 됩니다: ```bash parcel index.html @@ -48,7 +52,7 @@ parcel index.html 이제 브라우저에서 http://localhost:1234/ 에 접속하세요. 만약 빠른 모듈 교체가 동작하지 않는다면 [에디터 설정을 변경](hmr.html#safe-write)하셔야 합니다. 기본 포트번호를 `-p ` 옵션으로 덮어 쓸 수도 있습니다. -본인 소유의 서버가 없거나 완전히 클라이언트에서만 렌더되는 앱이라면 개발용 서버를 사용하세요. 만약 본인 소유의 서버가 있다면 `watch` 모드로 Parcel을 구동할 수 있습니다. 이 역시 파일 변화를 자동 리빌드(rebuild) 하고 빠른 모듈 교체를 지원합니다. 그러나 웹 서버를 시동시키지는 않습니다. +본인 소유의 서버가 없거나 완전히 클라이언트에서만 렌더되는 앱이라면 개발용 서버를 사용하세요. 만약 본인 소유의 서버가 있다면 `watch` 모드로 Parcel 을 구동할 수 있습니다. 이 역시 파일 변화를 자동 리빌드(rebuild) 하고 빠른 모듈 교체를 지원합니다. 그러나 웹 서버를 시동시키지는 않습니다. ```bash parcel watch index.html diff --git a/src/i18n/ko/docs/hmr.md b/src/i18n/ko/docs/hmr.md index bebceb624..a4b2fe049 100644 --- a/src/i18n/ko/docs/hmr.md +++ b/src/i18n/ko/docs/hmr.md @@ -1,38 +1,38 @@ # 🔥 빠른 모듈 교체(HMR) -빠른 모듈 교체(Hot Module Replacement)(이하 HMR)는 런타임에 페이지 새로고침 없이 모듈을 자동으로 갱신하므로 개발 경험을 향상시킵니다. 작은 변화에 따라 애플리케이션 상태를 계속 유지할 수 있습니다. Parcel HMR은 JavaScript와 CSS 애셋 모두를 지원합니다. 프로덕션 모드에서 HMR은 자동으로 비활성화 됩니다. +빠른 모듈 교체(Hot Module Replacement)(이하 HMR)는 런타임에 페이지 새로고침 없이 모듈을 자동으로 갱신하므로 개발 경험을 향상시킵니다. 작은 변화에 따라 애플리케이션 상태를 계속 유지할 수 있습니다. Parcel HMR 은 JavaScript 와 CSS 애셋 모두를 지원합니다. 프로덕션 모드에서 HMR 은 자동으로 비활성화 됩니다. -파일을 저장하면 Parcel은 변한 부분을 다시 빌드하고 이에 영향을 받는 모든 실행중인 클라이언트에 새 코드를 보냅니다. 그 후 새 코드는 이전 버전과 교체되고 모든 부모가 함께 다시 평가 됩니다. 이 과정 중 `module.hot` API를 사용해 훅(hook)을 걸수 있습니다. 이를 통해 모듈이 버려질 때, 또는 새 버전이 들어올 때 코드에 알려줄 수 있습니다. [react-hot-loader](https://github.com/gaearon/react-hot-loader)같은 프로젝트는 이 과정에 도움이 되며, Parcel에 바로 쓸 수 있습니다. +파일을 저장하면 Parcel 은 변한 부분을 다시 빌드하고 이에 영향을 받는 모든 실행중인 클라이언트에 새 코드를 보냅니다. 그 후 새 코드는 이전 버전과 교체되고 모든 부모가 함께 다시 평가 됩니다. 이 과정 중 `module.hot` API 를 사용해 훅(hook)을 걸수 있습니다. 이를 통해 모듈이 버려질 때, 또는 새 버전이 들어올 때 코드에 알려줄 수 있습니다. [react-hot-loader](https://github.com/gaearon/react-hot-loader)같은 프로젝트는 이 과정에 도움이 되며, Parcel 에 바로 쓸 수 있습니다. `module.hot.accept` 와 `module.hot.dispose` 두 메소드를 알아 두세요. `module.hot.accept`를 이 모듈이나 이 모듈의 다른 의존 사항이 갱신될 때 실행되는 콜백과 함께 호출합니다. `module.hot.dispose`는 이 모듈이 교체될 때 호출되는 콜백을 받아들입니다. ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // 모듈이 곧 폐기 됨 - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // 모듈이나 모듈의 의존 사항이 곧 갱신 됨 - }); + }) } ``` ## 의존성 자동설치 -Parcel은 의존성 패키지가 필요할때마다 `node_module`에서 맞는 의존성을 찾고, 만약 찾지 못하면 자동으로 `yarn`이나 `npm`을 이용해 의존성 패키지를 설치합니다.(`yarn.lock` 파일이 있는지 여부로 패키지 매니저 결정) 이 기능은 개발자로 하여금 의존성 패키지 설치를 위해 Parcel을 매번 종료하거나 여러개의 터미널을 띄우지 않아도 되게 해줍니다. +Parcel 은 의존성 패키지가 필요할때마다 `node_module`에서 맞는 의존성을 찾고, 만약 찾지 못하면 자동으로 `yarn`이나 `npm`을 이용해 의존성 패키지를 설치합니다.(`yarn.lock` 파일이 있는지 여부로 패키지 매니저 결정) 이 기능은 개발자로 하여금 의존성 패키지 설치를 위해 Parcel 을 매번 종료하거나 여러개의 터미널을 띄우지 않아도 되게 해줍니다. -이 기능은 오직 *개발모드*([`serve`](cli.md#serve) 혹은 [`watch`](cli.md#watch) 명령어 사용시)에서만 동작합니다. 하지만 프로덕션모드([`build`](cli.md#build) 명령어)에선 배포도중 발생하는 원치않는 부작용을 방지하기 위해 자동설치가 비활성화 됩니다. +이 기능은 오직 _개발모드_([`serve`](cli.md#serve) 혹은 [`watch`](cli.md#watch) 명령어 사용시)에서만 동작합니다. 하지만 프로덕션모드([`build`](cli.md#build) 명령어)에선 배포도중 발생하는 원치않는 부작용을 방지하기 위해 자동설치가 비활성화 됩니다. 이 기능은 [`--no-autoinstall`](cli.md#disable-autoinstall) 옵션으로 비활성화 할 수 있습니다. ## Safe Write -일부 텍스트 편집기와 IDE는 `safe write`라고 부르는 기능으로 파일을 복제한 다음 저장할 때 이름을 바꾸는 방식으로 데이터 유실을 방지합니다. +일부 텍스트 편집기와 IDE 는 `safe write`라고 부르는 기능으로 파일을 복제한 다음 저장할 때 이름을 바꾸는 방식으로 데이터 유실을 방지합니다. 빠른 모듈 교체를 사용할 때 이 기능은 자동 파일 변경 감지를 막아버립니다. `safe write` 기능을 비활성화 하려면 아래 제시된 방법을 사용하세요. -* `Sublime Text 3` 사용자 설정(user preferences)에 `atomic_save: "false"` 를 추가하세요. -* `IntelliJ` 설정(preferences)에서 "safe write"로 검색해서 찾은 뒤 비활성화 하세요. -* `Vim` 설정에 `:set backupcopy=yes` 를 추가하세요. -* `WebStorm` Preferences > Appearance & Behavior > System Settings 로 가서 `"safe write"`의 체크를 풀어버리세요. +- `Sublime Text 3` 사용자 설정(user preferences)에 `atomic_save: "false"` 를 추가하세요. +- `IntelliJ` 설정(preferences)에서 "safe write"로 검색해서 찾은 뒤 비활성화 하세요. +- `Vim` 설정에 `:set backupcopy=yes` 를 추가하세요. +- `WebStorm` Preferences > Appearance & Behavior > System Settings 로 가서 `"safe write"`의 체크를 풀어버리세요. diff --git a/src/i18n/ko/docs/how_it_works.md b/src/i18n/ko/docs/how_it_works.md index f25602689..cedacf1ef 100644 --- a/src/i18n/ko/docs/how_it_works.md +++ b/src/i18n/ko/docs/how_it_works.md @@ -1,16 +1,16 @@ # 🛠 어떻게 동작하는가 -Parcel은 **애셋** 트리를 **번들** 트리로 변환합니다. 다른 대부분의 번들러는 근본적으로 JavaScript 애셋에 기반하고 다른 포맷들이 여기에 붙어서 문자열로 JS 파일에 인라인 됩니다. Parcel은 파일형에 구속력이 없어서 어떤 유형의 애셋도 설정없이 작동합니다. Parcel 번들 과정에는 세 단계가 있습니다. +Parcel 은 **애셋** 트리를 **번들** 트리로 변환합니다. 다른 대부분의 번들러는 근본적으로 JavaScript 애셋에 기반하고 다른 포맷들이 여기에 붙어서 문자열로 JS 파일에 인라인 됩니다. Parcel 은 파일형에 구속력이 없어서 어떤 유형의 애셋도 설정없이 작동합니다. Parcel 번들 과정에는 세 단계가 있습니다. ### 1. 애셋 트리 구성 -Parcel은 하나의 진입 애셋을 입력으로 받습니다. 진입 애셋은 어느 유형이라도 가능합니다: JS 파일, HTML, CSS, 이미지 등. 다양한 [애셋 유형](asset_types.html)이 Parcel에 정의되어 있습니다. Parcel은 각 유형이 정확히 어떻게 다뤄져야 하는지 알고 있습니다. 애셋이 분석(parse)되면, 애셋의 의존 요소가 추출되고, 최종적인 컴파일 형태로 변환됩니다. 이것이 애셋 트리를 만듭니다. +Parcel 은 하나의 진입 애셋을 입력으로 받습니다. 진입 애셋은 어느 유형이라도 가능합니다: JS 파일, HTML, CSS, 이미지 등. 다양한 [애셋 유형](asset_types.html)이 Parcel 에 정의되어 있습니다. Parcel 은 각 유형이 정확히 어떻게 다뤄져야 하는지 알고 있습니다. 애셋이 분석(parse)되면, 애셋의 의존 요소가 추출되고, 최종적인 컴파일 형태로 변환됩니다. 이것이 애셋 트리를 만듭니다. ### 2. 번들 트리 구성 일단 애셋 트리가 만들어지면, 애셋은 번들 트리 안에 놓이게 됩니다. 진입 애셋을 위한 번들이 만들어지고, 코드 분할을 발생시키는 다이나믹 `import()`를 위한 하위 번들이 만들어 집니다. -형제 번들은 다른 유형의 애셋이 임포트 될 때 만들어 집니다. 예를 들자면 CSS 파일을 JavaScript에서 임포트 하는 경우, 대응하는 JavaScript에 대한 형제 번들 안에 위치하게 됩니다. +형제 번들은 다른 유형의 애셋이 임포트 될 때 만들어 집니다. 예를 들자면 CSS 파일을 JavaScript 에서 임포트 하는 경우, 대응하는 JavaScript 에 대한 형제 번들 안에 위치하게 됩니다. 만약 하나 이상의 번들에서 애셋이 필요하게 되면, 번들 트리 내의 가장 가까운 공통 조상번들로 끌어올려집니다. 이로써 중복 포함되는 일이 없어집니다. diff --git a/src/i18n/ko/docs/meta.json b/src/i18n/ko/docs/meta.json index f041f7bcc..b09531504 100644 --- a/src/i18n/ko/docs/meta.json +++ b/src/i18n/ko/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "ko" } -} \ No newline at end of file +} diff --git a/src/i18n/ko/docs/packagers.md b/src/i18n/ko/docs/packagers.md index c06769430..60bfaa2b6 100644 --- a/src/i18n/ko/docs/packagers.md +++ b/src/i18n/ko/docs/packagers.md @@ -1,26 +1,26 @@ # 📦 패키저 -Parcel에선 `패키저`가 다수의 `애셋`을 하나의 최종 출력 번들로 결합시킵니다. 이것은 모든 애셋이 처리되고, 하나의 번들 트리가 만들어 진 후 주 과정 중에 발생합니다. 패키저는 출력 파일 유형을 기반으로 등록되고, 해당 출력 타입을 생성한 애셋은 최종 출력 파일의 제품화를 위해 패키저로 보내집니다. +Parcel 에선 `패키저`가 다수의 `애셋`을 하나의 최종 출력 번들로 결합시킵니다. 이것은 모든 애셋이 처리되고, 하나의 번들 트리가 만들어 진 후 주 과정 중에 발생합니다. 패키저는 출력 파일 유형을 기반으로 등록되고, 해당 출력 타입을 생성한 애셋은 최종 출력 파일의 제품화를 위해 패키저로 보내집니다. ## 패키저 인터페이스 ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // 옵션. 필요하다면 파일 헤더 작성. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // 필수. 출력 파일에 애셋 작성. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // 옵션. 필요하다면 파일 트레일러 작성. - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MyPackager extends Packager { `addPackager` 메소드를 사용하여 번들러에 패키저를 등록할 수 있습니다. 이 메소드는 등록하려는 파일 유형과 패키저 모듈의 경로를 받아들입니다. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/ko/docs/plugins.md b/src/i18n/ko/docs/plugins.md index c128e35ec..02336ff55 100644 --- a/src/i18n/ko/docs/plugins.md +++ b/src/i18n/ko/docs/plugins.md @@ -1,22 +1,21 @@ # 🔌 플러그인 -Parcel은 대부분의 도구들과는 조금 다른 접근 방식을 취하고 있습니다. 추가적인 플러그인 설치나 설정 없이 다양한 일반적인 포맷을 즉시 지원할 수 있도록 포함하고 있습니다. 그러나 표준적이지 않은 방법으로 Parcel을 확장하고 싶은 경우가 있을것이며, 그런 경우를 위해 플러그인이 지원됩니다. 설치된 플러그인은 `package.json` 의존성(dependencies)을 기반으로 자동 감지되고 로드됩니다. +Parcel 은 대부분의 도구들과는 조금 다른 접근 방식을 취하고 있습니다. 추가적인 플러그인 설치나 설정 없이 다양한 일반적인 포맷을 즉시 지원할 수 있도록 포함하고 있습니다. 그러나 표준적이지 않은 방법으로 Parcel 을 확장하고 싶은 경우가 있을것이며, 그런 경우를 위해 플러그인이 지원됩니다. 설치된 플러그인은 `package.json` 의존성(dependencies)을 기반으로 자동 감지되고 로드됩니다. 새로운 파일 포맷에 대한 지원을 추가하는 경우 먼저 그것이 얼마나 널리 퍼져 있는지, 얼마나 표준적으로 구현되어 있는지를 고려해야 합니다. 만약 해당 포맷이 충분히 널리 퍼져있고 표준적이라면, 사용자가 설치해야 되는 플러그인 보다는 Parcel 코어에 추가되어야 합니다. 의문점이 있다면 [GitHub](https://github.com/parcel-bundler/parcel/issues)에서 논의해 주세요. ## 플러그인 API -Parcel 플러그인은 매우 단순합니다. Parcel 플러그인은 쉽게 말해 초기화 중 Parcel에 의해 자동으로 호출되는 단일 함수를 내보내는(export) 모듈입니다. 이 함수는 `Bundler` 객체를 입력으로 받고 애셋 유형과 패키저 등록과 같은 설정(configuration)을 수행할 수 있습니다. - +Parcel 플러그인은 매우 단순합니다. Parcel 플러그인은 쉽게 말해 초기화 중 Parcel 에 의해 자동으로 호출되는 단일 함수를 내보내는(export) 모듈입니다. 이 함수는 `Bundler` 객체를 입력으로 받고 애셋 유형과 패키저 등록과 같은 설정(configuration)을 수행할 수 있습니다. ```javascript -module.exports = function (bundler) { - bundler.addAssetType('ext', require.resolve('./MyAsset')); - bundler.addPackager('foo', require.resolve('./MyPackager')); -}; +module.exports = function(bundler) { + bundler.addAssetType('ext', require.resolve('./MyAsset')) + bundler.addPackager('foo', require.resolve('./MyPackager')) +} ``` -이 패키지를 `parcel-plugin-`접두어를 붙여 npm에 발행하면, 이 아래에서 설명하는바 대로 자동으로 감지되고 로드 됩니다. +이 패키지를 `parcel-plugin-`접두어를 붙여 npm 에 발행하면, 이 아래에서 설명하는바 대로 자동으로 감지되고 로드 됩니다. ## 플러그인 사용 diff --git a/src/i18n/ko/docs/production.md b/src/i18n/ko/docs/production.md index 477ee1277..3fdb8e5b9 100644 --- a/src/i18n/ko/docs/production.md +++ b/src/i18n/ko/docs/production.md @@ -1,6 +1,6 @@ # ✨ 프로덕션 -제품화를 위해 애플리케이션을 번들할 때가 왔다면, Parcel의 프로덕션(production) 모드를 사용하세요. +제품화를 위해 애플리케이션을 번들할 때가 왔다면, Parcel 의 프로덕션(production) 모드를 사용하세요. ```bash parcel build entry.js @@ -14,6 +14,6 @@ parcel build entry.js --out-dir build/output parcel build entry.js -d build/output ``` -감시(watch) 모드와 빠른 모듈 교체가 비활성화 되기 때문에 한 번 만 빌드 됩니다. 또한 출력 번들의 용량을 줄이기 위한 미니파이어(minifier)가 활성화 됩니다. Parcel은 JavaScript를 위해 [terser](https://github.com/fabiosantoscode/terser), CSS를 위해 [cssnano](http://cssnano.co), HTML을 위해 [htmlnano](https://github.com/posthtml/htmlnano)를 미니파이어로 사용합니다. +감시(watch) 모드와 빠른 모듈 교체가 비활성화 되기 때문에 한 번 만 빌드 됩니다. 또한 출력 번들의 용량을 줄이기 위한 미니파이어(minifier)가 활성화 됩니다. Parcel 은 JavaScript 를 위해 [terser](https://github.com/fabiosantoscode/terser), CSS 를 위해 [cssnano](http://cssnano.co), HTML 을 위해 [htmlnano](https://github.com/posthtml/htmlnano)를 미니파이어로 사용합니다. -프로덕션 모드 활성화는 또한 환경 변수를 `NODE_ENV=production`로 설정합니다. React와 같은 큰 라이브러리는 이 환경 변수를 설정함으로써 비활성화 되는 개발 전용 디버깅 요소가 있어 보다 작게 보다 빠르게 제품 빌드를 할 수 있습니다. +프로덕션 모드 활성화는 또한 환경 변수를 `NODE_ENV=production`로 설정합니다. React 와 같은 큰 라이브러리는 이 환경 변수를 설정함으로써 비활성화 되는 개발 전용 디버깅 요소가 있어 보다 작게 보다 빠르게 제품 빌드를 할 수 있습니다. diff --git a/src/i18n/ko/docs/recipes.md b/src/i18n/ko/docs/recipes.md index 31948e5cd..ae605abde 100644 --- a/src/i18n/ko/docs/recipes.md +++ b/src/i18n/ko/docs/recipes.md @@ -2,7 +2,7 @@ ## React -먼저 React를 위해 다음 의존성들을 설치합니다. +먼저 React 를 위해 다음 의존성들을 설치합니다. [Blog Post](http://blog.jakoblind.no/react-parcel/) @@ -31,7 +31,7 @@ yarn add --dev parcel-bundler ## Preact -먼저 Preact를 위해 다음 의존성들을 설치합니다. +먼저 Preact 를 위해 다음 의존성들을 설치합니다. ```bash npm install --save preact @@ -69,10 +69,9 @@ yarn add --dev babel-preset-preact } ``` - ## Vue -먼저, Vue를 사용하기 위해 의존성을 설치합니다. +먼저, Vue 를 사용하기 위해 의존성을 설치합니다. ```bash npm install --save vue diff --git a/src/i18n/ko/docs/transforms.md b/src/i18n/ko/docs/transforms.md index 7c8b15e2b..9e666f693 100644 --- a/src/i18n/ko/docs/transforms.md +++ b/src/i18n/ko/docs/transforms.md @@ -1,12 +1,12 @@ # 🐠 변환 -대부분의 번들러들이 애셋 변환(transform)을 위한 플러그인 설치와 설정(configuration)을 요구합니다. Parcel은 많은 수의 일반적인 변환과 트랜스파일러를 내장하여 지원합니다. [Babel](https://babeljs.io)을 사용하는 JavaScript, [PostCSS](http://postcss.org)을 사용하는 CSS, [PostHTML](https://github.com/posthtml/posthtml)을 사용하는 HTML을 변환할 수 있습니다. Parcel은 모듈 안에서 설정 파일(예: `.babelrc`, `.postcssrc`)을 발견했을 때 자동으로 이 변환을 실행합니다. +대부분의 번들러들이 애셋 변환(transform)을 위한 플러그인 설치와 설정(configuration)을 요구합니다. Parcel 은 많은 수의 일반적인 변환과 트랜스파일러를 내장하여 지원합니다. [Babel](https://babeljs.io)을 사용하는 JavaScript, [PostCSS](http://postcss.org)을 사용하는 CSS, [PostHTML](https://github.com/posthtml/posthtml)을 사용하는 HTML 을 변환할 수 있습니다. Parcel 은 모듈 안에서 설정 파일(예: `.babelrc`, `.postcssrc`)을 발견했을 때 자동으로 이 변환을 실행합니다. 써드파티(third-party) `node_modules`에서도 작동합니다. 만약 설정 파일이 패키지의 일부로 만들어지면 그 변환은 해당 모듈에서만 자동으로 켜집니다. 이것이 번들링을 빠르게 해줍니다. 오직 변환에 필요한 모듈만이 가공되기 때문입니다. 이는 또한 어떤 파일을 포함하고 제외하기 위해 수동으로 변환을 구성할 필요가 없음을 뜻합니다. 애플리케이션에 써드파티 코드를 사용하기 위해 그것이 어떻게 빌드 되었는지 알 필요가 없음을 의미합니다. ## Babel -[Babel](https://babeljs.io)은 커다란 플러그인 환경을 갖춘 인기있는 JavaScript 트랜스파일러입니다. Parcel을 Babel과 함께 사용하는 것은 독립형으로 사용 할 때나 다른 번들러와 함께 사용할 때와 똑같은 방식으로 작동합니다. +[Babel](https://babeljs.io)은 커다란 플러그인 환경을 갖춘 인기있는 JavaScript 트랜스파일러입니다. Parcel 을 Babel 과 함께 사용하는 것은 독립형으로 사용 할 때나 다른 번들러와 함께 사용할 때와 똑같은 방식으로 작동합니다. 플러그인과 프리셋을 앱에 설치 하세요: @@ -24,7 +24,7 @@ yarn add @babel/preset-env ## PostCSS -[PostCSS](http://postcss.org)는 plugin을 사용하여 CSS를 변환하는 도구입니다. [autoprefixer](https://github.com/postcss/autoprefixer), [cssnext](http://cssnext.io/), [CSS Modules](https://github.com/css-modules/css-modules)와 같이 말입니다. `.postcssrc` (JSON), `.postcssrc.js`, 또는 `postcss.config.js` 중 하나의 파일을 작성하여 Parcel로 PostCSS를 설정할 수 있습니다. +[PostCSS](http://postcss.org)는 plugin 을 사용하여 CSS 를 변환하는 도구입니다. [autoprefixer](https://github.com/postcss/autoprefixer), [cssnext](http://cssnext.io/), [CSS Modules](https://github.com/css-modules/css-modules)와 같이 말입니다. `.postcssrc` (JSON), `.postcssrc.js`, 또는 `postcss.config.js` 중 하나의 파일을 작성하여 Parcel 로 PostCSS 를 설정할 수 있습니다. 플러그인을 앱에 설치 하세요: @@ -54,29 +54,28 @@ Autoprefixer, cssnext 그리고 다른 도구의 대상 브라우저는 `.browse last 2 versions ``` -CSS Modules은 최상위 `modules` 키를 사용하여 약간 다른 방식으로 활성화 됩니다. CSS Modules은 JavaScript 번들에 포함될 객체를 내보내므로 Parcel로 하여금 특별한 지원을 필요로 하기 때문입니다. `postcss-modules`가 프로젝트 안에 설치되어야 함을 주의하세요. +CSS Modules 은 최상위 `modules` 키를 사용하여 약간 다른 방식으로 활성화 됩니다. CSS Modules 은 JavaScript 번들에 포함될 객체를 내보내므로 Parcel 로 하여금 특별한 지원을 필요로 하기 때문입니다. `postcss-modules`가 프로젝트 안에 설치되어야 함을 주의하세요. ### CSS 라이브러리와 같이 사용하기 -CSS 라이브러리와와 같이 사용하기 위해서는 그 라이브러리 안의 `.postcssrc` 에서 CSS Module을 지원해야 합니다. +CSS 라이브러리와와 같이 사용하기 위해서는 그 라이브러리 안의 `.postcssrc` 에서 CSS Module 을 지원해야 합니다. ### cssnano 코드 최소화 설정하기 -Parcel은 프로덕션 빌드를 할 때 [cssnano](http://cssnano.co)를 추가로 사용합니다. 기본 설정을 변경하고 싶다면 `cssnano.config.js` 파일을 생성해주세요. +Parcel 은 프로덕션 빌드를 할 때 [cssnano](http://cssnano.co)를 추가로 사용합니다. 기본 설정을 변경하고 싶다면 `cssnano.config.js` 파일을 생성해주세요. ```js module.exports = { calc: false, discardComments: { - removeAll: true, + removeAll: true } -}; +} ``` - ## PostHTML -[PostHTML](https://github.com/posthtml/posthtml) 플러그인으로 HTML을 변환하기 위한 도구입니다. `.posthtmlrc` (JSON), `posthtmlrc.js`, `posthtml.config.js` 중 하나의 파일을 작성하여 Parcel에 PostHTML을 설정할 수 있습니다. +[PostHTML](https://github.com/posthtml/posthtml) 플러그인으로 HTML 을 변환하기 위한 도구입니다. `.posthtmlrc` (JSON), `posthtmlrc.js`, `posthtml.config.js` 중 하나의 파일을 작성하여 Parcel 에 PostHTML 을 설정할 수 있습니다. 플러그인을 앱에 설치 하세요. @@ -98,9 +97,9 @@ yarn add posthtml-img-autosize 플러그인은 `plugins` 객체에 키로 지정되고 옵션은 객체의 값으로 정의 됩니다. 만약 플러그인에 옵션이 없다면, 대신 `true`로 설정하세요. - ## TypeScript -[TypeScript](https://www.typescriptlang.org/)는 타입이 추가된 JavaScript의 Superset 언어로, 컴파일하면 일반 JavaScript로 변환되며 최신 ES2015+ 기능들도 지원합니다. TypeScript의 변환 작업은 추가적인 설정 없이 가능합니다. + +[TypeScript](https://www.typescriptlang.org/)는 타입이 추가된 JavaScript 의 Superset 언어로, 컴파일하면 일반 JavaScript 로 변환되며 최신 ES2015+ 기능들도 지원합니다. TypeScript 의 변환 작업은 추가적인 설정 없이 가능합니다. ```html @@ -111,20 +110,21 @@ yarn add posthtml-img-autosize ``` + ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` + ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` - ## ReasonML/BuckleScript -[ReasonML](https://reasonml.github.io/)은 [BuckleScript](https://bucklescript.github.io)를 이용해 OCaml을 JavaScript로 컴파일합니다. 의존성을 설치하고 `bsconfig.json`을 만들면 ReasonML을 사용하실 수 있습니다. +[ReasonML](https://reasonml.github.io/)은 [BuckleScript](https://bucklescript.github.io)를 이용해 OCaml 을 JavaScript 로 컴파일합니다. 의존성을 설치하고 `bsconfig.json`을 만들면 ReasonML 을 사용하실 수 있습니다. ```bash $ yarn add bs-platform --dev @@ -145,8 +145,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, @@ -171,7 +170,7 @@ print_endline("Hello World"); ### ReasonReact -[ReasonReact](https://reasonml.github.io/reason-react/)는 ReasonML의 React 바인딩입니다. 역시 Parcel과 함께 이용 가능합니다. +[ReasonReact](https://reasonml.github.io/reason-react/)는 ReasonML 의 React 바인딩입니다. 역시 Parcel 과 함께 이용 가능합니다. ```bash $ yarn add react react-dom reason-react diff --git a/src/i18n/pl/docs/asset_types.md b/src/i18n/pl/docs/asset_types.md index 35a964aa3..a2eb2293b 100644 --- a/src/i18n/pl/docs/asset_types.md +++ b/src/i18n/pl/docs/asset_types.md @@ -7,14 +7,14 @@ Ponieważ Parcel przetwarza zasoby równolegle na wielu rdzeniach procesora, typ ## Interfejs Zasobu ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // zdefiniuj typ wyniku + type = 'foo' // zdefiniuj typ wyniku parse(code) { // parsuj kod do AST - return ast; + return ast } pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // zbierz informacje o zależnościach - this.addDependency('my-dep'); + this.addDependency('my-dep') } transform() { @@ -36,7 +36,7 @@ class MyAsset extends Asset { return { foo: 'my stuff here', // główny wynik js: 'some javascript' // dodatkowy wynik do umieszczenia w paczce JS, jeśli to konieczne - }; + } } } ``` @@ -46,8 +46,8 @@ class MyAsset extends Asset { Możesz zarejestrować swój typ zasobu w programie pakującym używając metody `addAssetType`. Akceptuje on rozszerzenie pliku do zarejestrowania i ścieżkę do modułu typu zasobu. Używana jest ścieżka zamiast faktycznego obiektu modułu dlatego, aby mogła być ona przekazana do procesów wątków usługowch. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/pl/docs/assets.md b/src/i18n/pl/docs/assets.md index 8922a1083..7c005a61c 100644 --- a/src/i18n/pl/docs/assets.md +++ b/src/i18n/pl/docs/assets.md @@ -8,35 +8,35 @@ Najbardziej tradycyjnym typem pliku dla programów tworzących pakiety jest Java ```javascript // Importuj moduł z użyciem składni CommonJS -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // Importuj moduł z użyciem składni modułów ES6 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` Możesz również importować zasoby nie-JavaScriptowe z pliku JavaScript, np. pliki CSS lub obrazy. Kiedy importujesz taki plik, nie jest on wstawiany w kod, jak ma to miejsce w innych programach tworzących pakiety. Zamiast tego, taki zasób umieszczany jest w osobnej paczce (np. w pliku CSS) razem z wszystkimi jego zależnościami. W [modułach CSS](https://github.com/css-modules/css-modules), eksportowane klasy są umieszczane w paczce JavaScript. Inne typy zasobów eksportują URL do pliku wyjściowego w paczce JavaScript, by odwołanie do niego mogło zostać wstawione w kod. ```javascript // Importuj plik CSS -import './test.css'; +import './test.css' // Importuj plik CSS z modułami CSS -import classNames from './test.css'; +import classNames from './test.css' // Importuj URL pliku obrazu -import imageURL from './test.png'; +import imageURL from './test.png' ``` Jeśli chcesz wstawić plik w kod w paczce wyjściowej JavaScript zamiast odwołania do niego poprzez URL, możesz użyć API `fs.readFileSync` z Node.js. URL-e muszą być możliwe do statycznej analizy, dlatego nie mogą posiadać żadnych zmiennych (oprócz `__dirname` i `__filename`). ```javascript -import fs from 'fs'; +import fs from 'fs' // Przeczytaj zawartość pliku jako string -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Przeczytaj zawartość pliku jako Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') ``` ## CSS diff --git a/src/i18n/pl/docs/code_splitting.md b/src/i18n/pl/docs/code_splitting.md index b4ad089cb..dfb519521 100644 --- a/src/i18n/pl/docs/code_splitting.md +++ b/src/i18n/pl/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // Renderuj stronę } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Renderuj stronę - page.render(); -}); + page.render() +}) ``` Ponieważ `import()` zwraca Promise, możesz również użyć składni async/await. Prawdopodobnie wymagana będzie konfiguracja Babel, by transpilować składnię, dopóki szersze wsparcie przez przeglądarki nie zostanie zapewnione. ```javascript -const page = await import('./pages/about'); +const page = await import('./pages/about') // Renderuj stronę -page.render(); +page.render() ``` Dynamiczne importy są w Parcel również wczytywane z opóźnieniem, dlatego możesz dalej umieszczać wszystkie swoje `import()`y na górze pliku, a paczki potomne i tak nie będą wczytane do czasu ich użycia. Poniższy przykład ilustruje, jak można wczytywać podstrony aplikacji z opóźnieniem. @@ -35,12 +36,12 @@ Dynamiczne importy są w Parcel również wczytywane z opóźnieniem, dlatego mo const pages = { about: import('./pages/about'), blog: import('./pages/blog') -}; +} async function renderPage(name) { // Wczytaj żądaną stronę z opóźnieniem. - const page = await pages[name]; - return page.render(); + const page = await pages[name] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +import 'babel-polyfill' +import './app' ``` Przeczytaj dokumentację na temat [babel-polyfill](http://babeljs.io/docs/usage/polyfill) i [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime). diff --git a/src/i18n/pl/docs/getting_started.md b/src/i18n/pl/docs/getting_started.md index b6c19c02b..c72b077d9 100644 --- a/src/i18n/pl/docs/getting_started.md +++ b/src/i18n/pl/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel to program tworzący pakiety do stron sieci web, wyróżniający się dzi Zainstaluj Parcel za pomocą Yarn lub npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Utwórz plik package.json w folderze projeku używając: ```bash yarn init -y ``` + or + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Następnie utwórz pliki index.html i index.js. ``` ```javascript -console.log("hello world"); +console.log('hello world') ``` Parcel ma wbudowany serwer deweloperski, który automatycznie przebudowuje aplikację po dokonaniu zmiany w pliku i wspiera [hot module replacement](hmr.html) aby przyspieszyć tworzenie oprogramowania. Po prostu podaj mu twój plik wejściowy: diff --git a/src/i18n/pl/docs/hmr.md b/src/i18n/pl/docs/hmr.md index 98eb5c3c7..c5385f4bc 100644 --- a/src/i18n/pl/docs/hmr.md +++ b/src/i18n/pl/docs/hmr.md @@ -8,12 +8,12 @@ Są dwie metody o których powinno się wiedzieć: `module.hot.accept` i `module ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // moduł zaraz zostanie zastąpiony - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // moduł lub którakolwiek z jego zależności został właśnie zaktualizowany - }); + }) } ``` diff --git a/src/i18n/pl/docs/meta.json b/src/i18n/pl/docs/meta.json index ea67d249f..7f301d60b 100644 --- a/src/i18n/pl/docs/meta.json +++ b/src/i18n/pl/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "pl" } -} \ No newline at end of file +} diff --git a/src/i18n/pl/docs/packagers.md b/src/i18n/pl/docs/packagers.md index aae2f78fe..3c1dfd014 100644 --- a/src/i18n/pl/docs/packagers.md +++ b/src/i18n/pl/docs/packagers.md @@ -5,22 +5,22 @@ W Parcel, `Program pakujący` łączy wiele `Zasobów` do finalnej paczki wyjśc ## Interfejs Programu Pakującego ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // opcjonalne. zapisz nagłówek pliku jeśli to konieczne. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // wymagane. zapisz zasób do pliku wyjściowego. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // opcjonalne. zapisz końcówkę pliku jeśli to konieczne. - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MyPackager extends Packager { Możesz zarejestrować swój program pakujący w Parcel za pomocą metody `addPackager`. Przyjmuje ona typ pliku do rejestracji i ścieżkę do modułu programu pakującego. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/pl/docs/plugins.md b/src/i18n/pl/docs/plugins.md index 1553512e9..caccdfba1 100644 --- a/src/i18n/pl/docs/plugins.md +++ b/src/i18n/pl/docs/plugins.md @@ -9,10 +9,10 @@ Dodając wsparcie dla nowego typu pliku do Parcel, powinno się najpierw rozważ Wtyczki Parcel są wyjątkowo proste. To zwyczajne moduły, które eksportują pojedynczą funkcję, która wywoływana jest przez Parcel automatycznie podczas inicjalizacji. Funkcja otrzymuje na wejściu obiekt `Bundler` i może skonfigurować wtyczkę, np. rejestrując typy zasobów i programy pakujące. ```javascript -module.exports = function (bundler) { - bundler.addAssetType('ext', require.resolve('./MyAsset')); - bundler.addPackager('foo', require.resolve('./MyPackager')); -}; +module.exports = function(bundler) { + bundler.addAssetType('ext', require.resolve('./MyAsset')) + bundler.addPackager('foo', require.resolve('./MyPackager')) +} ``` Opublikuj gotową paczkę na npm używając nazwy z prefiksem `parcel-plugin-`, a zostanie ona automatycznie wykryta i załadowana jak opisano poniżej. diff --git a/src/i18n/pl/docs/production.md b/src/i18n/pl/docs/production.md index 15e9f87b1..adf97fb81 100644 --- a/src/i18n/pl/docs/production.md +++ b/src/i18n/pl/docs/production.md @@ -10,7 +10,6 @@ Tryb produkcyjny wyłącza tryb `watch` i hot module replacement, a więc kod zo Włączenie trybu produkcyjnego ustawia także zmienną systemową `NODE_ENV=production`. Duże biblioteki, takie jak React, mają specjalne funkcje przeznaczone wyłącznie do debuggingu i są wyłączane poprzez ustawienie tej zmiennej systemowej, co powoduje redukcję rozmiaru plików wyjściowych i szybszy proces budowania. - ### Opcje #### Ustawienie folderu wyjściowego @@ -46,7 +45,6 @@ lub ``` - #### Wyłączanie minifikacji Domyślnie: minifikacja włączona diff --git a/src/i18n/pl/docs/transforms.md b/src/i18n/pl/docs/transforms.md index 6b0dc2f4f..b87bada57 100644 --- a/src/i18n/pl/docs/transforms.md +++ b/src/i18n/pl/docs/transforms.md @@ -24,7 +24,7 @@ Następnie utwórz plik `.babelrc`: ## PostCSS -[PostCSS](http://postcss.org) to narzędzie do transformacji CSS z użyciem wtyczek, np. [autoprefixer](https://github.com/postcss/autoprefixer), [cssnext](http://cssnext.io/) czy [CSS Modules](https://github.com/css-modules/css-modules). Możesz skonfigurować PostCSS z Parcel tworząc plik konfiguracyjny o jednej z nazw: `.postcssrc` (JSON), `.postcssrc.js` lub `postcss.config.js`. +[PostCSS](http://postcss.org) to narzędzie do transformacji CSS z użyciem wtyczek, np. [autoprefixer](https://github.com/postcss/autoprefixer), [cssnext](http://cssnext.io/) czy [CSS Modules](https://github.com/css-modules/css-modules). Możesz skonfigurować PostCSS z Parcel tworząc plik konfiguracyjny o jednej z nazw: `.postcssrc` (JSON), `.postcssrc.js` lub `postcss.config.js`. Zainstaluj wtyczki w aplikacji wykonując: @@ -81,6 +81,7 @@ Następnie utwórz plik `.posthtmlrc`: Wtyczki są wymienione w obiekcie `plugins` jako klucze, a ich opcje są definiowane poprzez wartości. Jeśli nie istnieje potrzeba określania opcji dla wtyczki, ustaw jej wartość na `true`. ## TypeScript + [TypeScript](https://www.typescriptlang.org/) to typowany nadzbiór JavaScript, który kompiluje się do JavaScript, który wspiera także funkcje ES2015+. Transformacja TypeScript działa od razu bez żadnej dodatkowej konfiguracji. ```html @@ -91,14 +92,16 @@ Wtyczki są wymienione w obiekcie `plugins` jako klucze, a ich opcje są definio ``` + ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` + ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` ## ReasonML/BuckleScript @@ -124,8 +127,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, diff --git a/src/i18n/pt/docs/api.md b/src/i18n/pt/docs/api.md index e4997cd16..2c7751ae7 100644 --- a/src/i18n/pt/docs/api.md +++ b/src/i18n/pt/docs/api.md @@ -2,8 +2,9 @@ ## Bundler -Ao invés do cliente, você pode utilizar a API para inicializar o *bundler*, para casos mais avançados (por exemplo, um processamento customizado após cada *build*). +Ao invés do cliente, você pode utilizar a API para inicializar o _bundler_, para casos mais avançados (por exemplo, um processamento customizado após cada _build_). Um exemplo com toda opção explicada: + ```Javascript const Bundler = require('parcel-bundler'); const Path = require('path'); @@ -53,9 +54,10 @@ runBundle(); ### Eventos -Esta é a lista com todos os eventos do *bundler*: +Esta é a lista com todos os eventos do _bundler_: + +- `bundled` será chamado uma única vez quando o Parcel terminar de construir **pela primeira vez** com sucesso, a instância do [bundle](#bundle) principal é passada para este callback. -* `bundled` será chamado uma única vez quando o Parcel terminar de construir **pela primeira vez** com sucesso, a instância do [bundle](#bundle) principal é passada para este callback. ```Javascript const bundler = new Bundler(...); bundler.on('bundled', (bundle) => { @@ -65,7 +67,8 @@ bundler.on('bundled', (bundle) => { bundler.bundle(); ``` -* `buildEnd` gerá chamado após cada build (aka **incluindo cada rebuild**), isto também emite se algum erro ocorreu. +- `buildEnd` gerá chamado após cada build (aka **incluindo cada rebuild**), isto também emite se algum erro ocorreu. + ```Javascript const bundler = new Bundler(...); bundler.on('buildEnd', () => { @@ -75,7 +78,8 @@ bundler.on('buildEnd', () => { bundler.bundle(); ``` -* `buildStart` será chamado no começo do primeiro build, o array `entryFiles` será passado para esse callback +- `buildStart` será chamado no começo do primeiro build, o array `entryFiles` será passado para esse callback + ```Javascript const bundler = new Bundler(...); bundler.on('buildStart', entryPoints => { @@ -85,7 +89,8 @@ bundler.on('buildStart', entryPoints => { bundler.bundle(); ``` -* `buildError` será chamado sempre que ocorrer um erro durante os builds, o objeto `Error` será passado para esse callback +- `buildError` será chamado sempre que ocorrer um erro durante os builds, o objeto `Error` será passado para esse callback + ```Javascript const bundler = new Bundler(...); bundler.on('buildError', error => { @@ -101,21 +106,20 @@ Um `Bundle` é o que o Parcel utiliza para juntar todos os assets juntos, isto c #### Propriedades -* `type`: Os tipos dos assets contidos (por exemplo: js, css, map, ...) -* `name`: O nome do bundle (gerado utilizando `Asset.generateBundleName()` de `entryAsset`) -* `parentBundle`: O bundle pai, é null em caso de ser o bundle de entrada -* `entryAsset`: O entrypoint do bundle, usado para gerar o nome e coletar os assets. -* `assets`: Um `Set` com todos os assets dentro do bundle -* `childBundles`: Um `Set` com todos os bundles filhos -* `siblingBundles`: Um `Set` com todos os bundles irmãos -* `siblingBundlesMap`: Um `Map` de todos os bundles irmãos -* `offsets`: Um `Map` de todas as localizações do assets dentro do bundle, utilizado para gerar os source maps +- `type`: Os tipos dos assets contidos (por exemplo: js, css, map, ...) +- `name`: O nome do bundle (gerado utilizando `Asset.generateBundleName()` de `entryAsset`) +- `parentBundle`: O bundle pai, é null em caso de ser o bundle de entrada +- `entryAsset`: O entrypoint do bundle, usado para gerar o nome e coletar os assets. +- `assets`: Um `Set` com todos os assets dentro do bundle +- `childBundles`: Um `Set` com todos os bundles filhos +- `siblingBundles`: Um `Set` com todos os bundles irmãos +- `siblingBundlesMap`: Um `Map` de todos os bundles irmãos +- `offsets`: Um `Map` de todas as localizações do assets dentro do bundle, utilizado para gerar os source maps #### Árvore O `Bundle` contém `parentBundle`, `childBundles` e `siblingBundles`, todas essas propriedades juntas cria um iterável rápido para percorrer a árvore do bundle. - Um exemplo muito básico de uma árvore de asset e gerando uma árvore de bundle. ##### Árvore de assets: @@ -158,6 +162,7 @@ index.html Middleware pode ser utilizado como hoot dentro do servidor http (por exemplo, `express` ou `http` Node) Um exemplo de uso de middleware do Parcel com o express: + ```Javascript const Bundler = require('parcel-bundler'); const app = require('express')(); diff --git a/src/i18n/pt/docs/asset_types.md b/src/i18n/pt/docs/asset_types.md index c660214de..04ac3c8c5 100644 --- a/src/i18n/pt/docs/asset_types.md +++ b/src/i18n/pt/docs/asset_types.md @@ -7,14 +7,14 @@ Como o Parcel processa recursos em paralelo através de vários núcleos do proc ## Interface Asset ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // define o tipo de saída principal. + type = 'foo' // define o tipo de saída principal. async parse(code) { // analisar o código em um AST - return ast; + return ast } async pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // analisa as dependências - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { @@ -43,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', // rendição alternativa a ser colocada no pacote JS, caso necessário sourceMap } - ]; + ] } async postProcess(generated) { @@ -60,8 +60,8 @@ module.exports = MyAsset Você pode registrar seu tipo de recurso com um empacotador usando o método `addAssetType`. Ele aceita uma extensão de arquivo para se registrar e o caminho para seu módulo do tipo de recurso. É apenas um caminho e não o objeto real, para que ele possa ser enviado para os processos. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/pt/docs/cli.md b/src/i18n/pt/docs/cli.md index c55ded324..3495ef5a5 100644 --- a/src/i18n/pt/docs/cli.md +++ b/src/i18n/pt/docs/cli.md @@ -4,7 +4,7 @@ ### Servir -Inicia um servidor de desenvolvimento, que recriará automaticamente seu aplicativo ao alterar os arquivos e oferece suporte à [*hot module replacement*](hmr.html) para desenvolvimento rápido. +Inicia um servidor de desenvolvimento, que recriará automaticamente seu aplicativo ao alterar os arquivos e oferece suporte à [_hot module replacement_](hmr.html) para desenvolvimento rápido. ```bash parcel index.html @@ -18,7 +18,7 @@ Constrói os recursos uma vez, ele também habilita minificação e define a var parcel build index.html ``` -### *Watch* +### _Watch_ O comando `watch` é similar ao `server`, com a principal diferença sendo a de não iniciar um servidor. @@ -137,12 +137,12 @@ Disponível em: `serve`, `watch`, `build` parcel entry.js --log-level 1 ``` -| Nível | Efeito | -|--- |--- | -| 0 | Desabilitado | -| 1 | Somente erros | -| 2 | Erros e Avisos | -| 3 | Tudo | +| Nível | Efeito | +| ----- | -------------- | +| 0 | Desabilitado | +| 1 | Somente erros | +| 2 | Erros e Avisos | +| 3 | Tudo | ### Hostname HMR @@ -174,11 +174,11 @@ Disponível em: `serve`, `watch`, `build` parcel build entry.js --out-file output.html ``` -Isso altera o nome de arquivo de saída no *entrypoint* do pacote +Isso altera o nome de arquivo de saída no _entrypoint_ do pacote -### Exibir um *report* detalhado +### Exibir um _report_ detalhado -Padrão: *report* mínimo +Padrão: _report_ mínimo Disponível em: `build` @@ -196,7 +196,7 @@ Disponível em: `serve`, `watch` (listen on HTTPS for HMR connections) parcel build entry.js --https ``` -⚠️ Esta *flag* gera um certificado auto-assinado, você pode ter que configurar seu navegador para permitir certificados auto-assinado para localhost. +⚠️ Esta _flag_ gera um certificado auto-assinado, você pode ter que configurar seu navegador para permitir certificados auto-assinado para localhost. ### Definir um certificado customizado @@ -288,4 +288,4 @@ Disponível em: `build` parcel build entry.js --experimental-scope-hoisting ``` -Para obter mais informações, consulte a [sessão *Tree Shaking*](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) no post de Devon Govett no pacote 1,9. +Para obter mais informações, consulte a [sessão _Tree Shaking_](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) no post de Devon Govett no pacote 1,9. diff --git a/src/i18n/pt/docs/code_splitting.md b/src/i18n/pt/docs/code_splitting.md index a46c67873..c3b2efb8e 100644 --- a/src/i18n/pt/docs/code_splitting.md +++ b/src/i18n/pt/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // Renderizar a página } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Renderizar a página - page.render(); -}); + page.render() +}) ``` Como `import ()` retorna uma Promise, você também pode usar async/await. Provavelmente você precisará configurar o Babel para converter a sintaxe até que ela seja suportada por todos os navegadores. ```javascript -const page = await import('./pages/about'); +const page = await import('./pages/about') // Renderizar a página -page.render(); +page.render() ``` As importações dinâmicas também são carregadas sob demanda no Parcel, assim você ainda pode colocar todas as suas chamadas `import()` no topo do seu arquivo e os pacotes secundários não serão carregados até serem utilizados. O exemplo a seguir mostra como você poderia carregar outras páginas da sua aplicação de forma dinâmica. @@ -35,12 +36,12 @@ As importações dinâmicas também são carregadas sob demanda no Parcel, assim const pages = { about: import('./pages/about'), blog: import('./pages/blog') -}; +} async function renderPage(name) { // Carregue a página sob demanda quando ela for requisitada - const page = await pages[name]; - return page.render(); + const page = await pages[name] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +import 'babel-polyfill' +import './app' ``` Leia a documentação em [babel-polyfill](http://babeljs.io/docs/usage/polyfill) e [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime). diff --git a/src/i18n/pt/docs/coffeeScript.md b/src/i18n/pt/docs/coffeeScript.md index 7cce68e83..a85408179 100644 --- a/src/i18n/pt/docs/coffeeScript.md +++ b/src/i18n/pt/docs/coffeeScript.md @@ -1,3 +1,3 @@ # CoffeeScript -*Extensões suportadas: `coffee`* +_Extensões suportadas: `coffee`_ diff --git a/src/i18n/pt/docs/css.md b/src/i18n/pt/docs/css.md index e47753b5a..8cea99c7f 100644 --- a/src/i18n/pt/docs/css.md +++ b/src/i18n/pt/docs/css.md @@ -1,8 +1,8 @@ # CSS -*Extensões suportadas: `css`, `pcss`, `postcss`* +_Extensões suportadas: `css`, `pcss`, `postcss`_ -Recursos CSS podem ser importados de um arquivo Javascript ou HTML, e podem conter dependências referenciadas pela sintaxe `@import`, bem como referências a imagens, fontes, etc. através da função `url()`. Outros arquivos CSS que são `@import`ados de forma *inline* no mesmo pacote CSS e referenciadas com `url()` serão reescritas em seus nomes de arquivos de saída. Todos os nomes de arquivos devem ser relativos ao arquivo CSS atual. +Recursos CSS podem ser importados de um arquivo Javascript ou HTML, e podem conter dependências referenciadas pela sintaxe `@import`, bem como referências a imagens, fontes, etc. através da função `url()`. Outros arquivos CSS que são `@import`ados de forma _inline_ no mesmo pacote CSS e referenciadas com `url()` serão reescritas em seus nomes de arquivos de saída. Todos os nomes de arquivos devem ser relativos ao arquivo CSS atual. ```css /* Importando outro arquivo CSS */ @@ -56,15 +56,18 @@ Para que os módulos CSS funcionem corretamente com os módulos existentes, eles ## Definindo a configuração de Minificação do cssnano -Parcel adiciona o [cssnano](http://cssnano.co) ao postcss para minificar o css em *build* de produção, onde configurações customizadas podem ser definidas ao criar o arquivo `cssnano.config.js`: +Parcel adiciona o [cssnano](http://cssnano.co) ao postcss para minificar o css em _build_ de produção, onde configurações customizadas podem ser definidas ao criar o arquivo `cssnano.config.js`: ```js module.exports = { - preset: ['default', { - calc: false, - discardComments: { - removeAll: true, + preset: [ + 'default', + { + calc: false, + discardComments: { + removeAll: true + } } - }] -}; + ] +} ``` diff --git a/src/i18n/pt/docs/env.md b/src/i18n/pt/docs/env.md index 7e0cab3e5..a71ad936a 100644 --- a/src/i18n/pt/docs/env.md +++ b/src/i18n/pt/docs/env.md @@ -6,12 +6,12 @@ Arquivos `.env` devem ser armazenados junto com o `package.json` que contém sua Parcel carrega arquivos `.env` com esses nomes especificos para os valores de `NODE_ENV` seguintes: -| Nome de arquivos `.env` válidos | `NODE_ENV=\*` | `NODE_ENV=test` | -| --------------------------------- | ------------- | --------------- | -| `.env` | ✔️ | ✔️ | -| `.env.local` | ✔️ | ✖️ | -| `.env.${NODE_ENV}` | ✔️ | ✔️ | -| `.env.${NODE_ENV}.local` | ✔️ | ✔️ | +| Nome de arquivos `.env` válidos | `NODE_ENV=\*` | `NODE_ENV=test` | +| ------------------------------- | ------------- | --------------- | +| `.env` | ✔️ | ✔️ | +| `.env.local` | ✔️ | ✖️ | +| `.env.${NODE_ENV}` | ✔️ | ✔️ | +| `.env.${NODE_ENV}.local` | ✔️ | ✔️ | Notavelmente: diff --git a/src/i18n/pt/docs/getting_started.md b/src/i18n/pt/docs/getting_started.md index 032b92c1c..217cae3c5 100644 --- a/src/i18n/pt/docs/getting_started.md +++ b/src/i18n/pt/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel é um empacotador de aplicações web, diferenciado pela experiência do Primeiro, instale o Parcel usando Yarn ou npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ Crie o arquivo package.json no diretório do seu projeto executando: ```bash yarn init -y ``` + ou + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Depois, crie os arquivos index.html e index.js. ``` ```javascript -console.log("Olá, mundo!"); +console.log('Olá, mundo!') ``` Parcel possui um servidor de desenvolvimento embutido, o qual irá reconstruir sua aplicação automaticamente à medida que você vai alterando os arquivos. Ele suporta [Hot Module Replacement](hmr.html) para acelerar o desenvolvimento. Apenas aponte a ele seu arquivo de entrada: @@ -59,16 +63,19 @@ parcel watch index.html No caso de você ter mais de um arquivo de entrada, vamos dizer `index.html` e `about.html`, você tem duas maneiras de executar o bundler: Especificando os nomes dos arquivos: + ```bash parcel index.html about.html ``` Utilizando tokens e criando um glob: + ```bash parcel *.html ``` -*NOTA:* No caso de você possuir uma estrutura de arquivos como esta: +_NOTA:_ No caso de você possuir uma estrutura de arquivos como esta: + ``` - diretorio-1 -- index.html @@ -76,7 +83,7 @@ parcel *.html -- index.html ``` -Acessar http://localhost:1234/diretorio-1/ não irá funcionar, você terá que apontar explicitamente para o arquivo http://localhost:1234/diretorio-1/index.html. +Acessar http://localhost:1234/diretorio-1/ não irá funcionar, você terá que apontar explicitamente para o arquivo http://localhost:1234/diretorio-1/index.html. ### Construindo para Produção diff --git a/src/i18n/pt/docs/graphQL.md b/src/i18n/pt/docs/graphQL.md index e05cd4bf4..4f5d60e34 100644 --- a/src/i18n/pt/docs/graphQL.md +++ b/src/i18n/pt/docs/graphQL.md @@ -1,3 +1,3 @@ # GraphQL -*Extensões suportadas: `gql`, `graphql`* +_Extensões suportadas: `gql`, `graphql`_ diff --git a/src/i18n/pt/docs/hmr.md b/src/i18n/pt/docs/hmr.md index d9784dcc4..837c43002 100644 --- a/src/i18n/pt/docs/hmr.md +++ b/src/i18n/pt/docs/hmr.md @@ -8,13 +8,13 @@ Existem dois métodos que você precisa conhecer: `module.hot.accept` e `module. ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // Módulo que está prestes a ser substituído - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // Módulo ou uma de suas dependências que acabaram de ser atualizados - }); + }) } ``` @@ -22,16 +22,17 @@ if (module.hot) { Sempre que o Parcel vê uma dependência que se encaixa o padrão `node_module` e não pode encontrá-la, tenta-se instalar essa dependência usando `yarn` ou `npm` dependendo se encontrar um arquivo `yarn.lock` ou não. Isso evita que o desenvolvedor tenha que sair do pacote ou ter várias janelas de terminal abertas. -Isto ocorre somente em *development* (utilizando [`serve`](cli.md#serve) ou [`watch`](cli.md#watch)), no entanto, em produção (utilizando [`build`](cli.md#build)) a instalação automática é desabilitada para evitar efeitos colaterais indesejados na implantação. +Isto ocorre somente em _development_ (utilizando [`serve`](cli.md#serve) ou [`watch`](cli.md#watch)), no entanto, em produção (utilizando [`build`](cli.md#build)) a instalação automática é desabilitada para evitar efeitos colaterais indesejados na implantação. Você pode desabilitar este recurso utilizando [`--no-autoinstall`](cli.md#disable-autoinstall). ## Safe Write + Alguns editores de texto e IDE têm um recurso chamado `safe write`, isto basicamente impede a perda de dados, criando uma cópia do arquivo e o renomeando quando salvo. -Quando o recurso *Hot Module Reload (HMR)* é utilizado, é bloqueada a detecção automatica de mudanças em arquivos, para desabilitar o `safe write` utilize uma das opções fornecidas abaixo: +Quando o recurso _Hot Module Reload (HMR)_ é utilizado, é bloqueada a detecção automatica de mudanças em arquivos, para desabilitar o `safe write` utilize uma das opções fornecidas abaixo: -* `Sublime Text 3` adicione `atomic_save: "false"` às suas preferências de usuário. -* `IntelliJ` use a pesquisa nas preferências para encontrar "safe write" e desativá-lo. -* `Vim` adicione `:set backupcopy=yes` em suas configurações. -* `WebStorm` desmarque `Use "safe write"` em Preferências > Aparência & Comportamento > Configurações do Sistema (*Preferences > Appearance & Behavior > System Settings*). +- `Sublime Text 3` adicione `atomic_save: "false"` às suas preferências de usuário. +- `IntelliJ` use a pesquisa nas preferências para encontrar "safe write" e desativá-lo. +- `Vim` adicione `:set backupcopy=yes` em suas configurações. +- `WebStorm` desmarque `Use "safe write"` em Preferências > Aparência & Comportamento > Configurações do Sistema (_Preferences > Appearance & Behavior > System Settings_). diff --git a/src/i18n/pt/docs/html.md b/src/i18n/pt/docs/html.md index ecf95e8a0..92a9bc7a5 100644 --- a/src/i18n/pt/docs/html.md +++ b/src/i18n/pt/docs/html.md @@ -1,6 +1,6 @@ # HTML -*Extensões suportadas: `htm`, `html`* +_Extensões suportadas: `htm`, `html`_ Arquivos HTML são frequentemente utilizados como ponto de entrada para o Parcel, mas também podem ser referenciados pelos arquivos JavaScript, por exemplo, para fornecer links para outras páginas. Os endereços dos scripts, estilos, mídias e outros arquivos HTML são extraídos e compilados como descrito acima. As referências são reescritas no HTML para que elas sejam referenciadas corretamente. Todos os nomes dos arquivos devem ser relativos ao arquivo HTML principal. diff --git a/src/i18n/pt/docs/javascript.md b/src/i18n/pt/docs/javascript.md index a2124e8c3..fc0c65fee 100644 --- a/src/i18n/pt/docs/javascript.md +++ b/src/i18n/pt/docs/javascript.md @@ -1,28 +1,28 @@ # Javascript -*Extensões suportadas: `js`, `jsx`, `es6`, `jsm`, `mjs`* +_Extensões suportadas: `js`, `jsx`, `es6`, `jsm`, `mjs`_ O tipo de arquivo mais utilizado pelos empacotadores é o JavaScript. Parcel suporta tanto CommonJS como módulos ES6 para importar os arquivos. Ele também suporta a função `import()` para carregar os módulos de forma assíncrona, o qual será discutido na sessão [separação do código](code_splitting.html). ```javascript // Importar um módulo utilizando sintaxe CommonJS -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // Importar um módulo utilizando sintaxe ES6 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` Você também pode importar outros tipos de recursos que não sejam arquivos JavaScript, como um arquivo CSS ou mesmo uma imagem. Quando você importar um desses tipos de arquivos, eles não serão incluídos no arquivo principal assim como é feito com os outros empacotadores. Na verdade, eles serão adicionados em arquivos separados (por exemplo, um arquivo CSS) junto com suas dependências. Quando você utilizar [CSS Modules](https://github.com/css-modules/css-modules), as classes exportadas são adicionadas no arquivo de saída JavaScript. Outros tipos de recursos exportam a referência no arquivo de saída JavaScript para que você possa referenciar no seu código. ```javascript // Importando um arquivo CSS -import './test.css'; +import './test.css' // Importando um arquivo CSS com CSS modules -import classNames from './test.css'; +import classNames from './test.css' // Importando a URL de um arquivo de imagem -import imageURL from './test.png'; +import imageURL from './test.png' // Import um arquivo HTML import('./some.html') @@ -35,16 +35,16 @@ require('./some.html') Caso você queira adicionar um arquivo dentro do arquivo de saída JavaScript, ao invés de referenciar o endereço, você pode utilizar a API `fs.readFileSync` do Node.js para fazer isso. O endereço precisa ser estaticamente analisado, ou seja, ele não pode conter variáveis (diferente de `__dirname` e `__filename`). ```javascript -import fs from 'fs'; +import fs from 'fs' // Lendo o conteúdo como uma string -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Lendo o coteúdo como um Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') // Convertendo o conteúdo do Buffer em uma imagem - +; ``` # Babel @@ -61,18 +61,16 @@ Crie o arquivo `.babelrc`: ```json { - "presets": [ - "@babel/preset-env" - ] + "presets": ["@babel/preset-env"] } ``` ## Conversões padrões do Babel -Parcel transpila o seu código com `@babel/preset-env` por padrão, isto é para transpilar cada modulo interno (*local requires*) e externo (*node_modules*) para coincidir com destino definido. +Parcel transpila o seu código com `@babel/preset-env` por padrão, isto é para transpilar cada modulo interno (_local requires_) e externo (_node_modules_) para coincidir com destino definido. -Para o alvo `browser` é utilizado o [browserslist](https://github.com/browserslist/browserslist), o *browserlist* alvo pode ser definido no `package.json` (`engines.browsers` ou `browserslist`) ou usando um arquivo de configuração (`browserslist` ou `.browserslistrc`). +Para o alvo `browser` é utilizado o [browserslist](https://github.com/browserslist/browserslist), o _browserlist_ alvo pode ser definido no `package.json` (`engines.browsers` ou `browserslist`) ou usando um arquivo de configuração (`browserslist` ou `.browserslistrc`). -O alvo padrão do *browserlist* é: `> 0.25%` (Significando, suportar cada navegador que tenha 0,25% ou mais da quantidade total de usuários ativos da web) +O alvo padrão do _browserlist_ é: `> 0.25%` (Significando, suportar cada navegador que tenha 0,25% ou mais da quantidade total de usuários ativos da web) -Para o alvo `node`, Parcel utiliza o `engines.node` definido no `package.json`, este padrão para *node 8*. +Para o alvo `node`, Parcel utiliza o `engines.node` definido no `package.json`, este padrão para _node 8_. diff --git a/src/i18n/pt/docs/json.md b/src/i18n/pt/docs/json.md index 82965f92d..657801888 100644 --- a/src/i18n/pt/docs/json.md +++ b/src/i18n/pt/docs/json.md @@ -1,3 +1,3 @@ # JSON -*Extensões suportadas: `json`, `json5`* +_Extensões suportadas: `json`, `json5`_ diff --git a/src/i18n/pt/docs/less.md b/src/i18n/pt/docs/less.md index 9554d7398..5622b7b74 100644 --- a/src/i18n/pt/docs/less.md +++ b/src/i18n/pt/docs/less.md @@ -1,3 +1,3 @@ # LESS -*Extensões suportadas: `less`* +_Extensões suportadas: `less`_ diff --git a/src/i18n/pt/docs/meta.json b/src/i18n/pt/docs/meta.json index 648e53e7b..c5bf5c55e 100644 --- a/src/i18n/pt/docs/meta.json +++ b/src/i18n/pt/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "pt" } -} \ No newline at end of file +} diff --git a/src/i18n/pt/docs/module_resolution.md b/src/i18n/pt/docs/module_resolution.md index 149052197..9a7cc2c23 100644 --- a/src/i18n/pt/docs/module_resolution.md +++ b/src/i18n/pt/docs/module_resolution.md @@ -4,7 +4,7 @@ Parcel (v.1.7.0 e superior) suporta estratégias de múltilplas resoluções de Termos Notáveis: -- **raiz do projeto**: o diretório do *entrypoint* especificado para o Parcel, ou a raiz compartilhada (diretório pai em comum) quando múltiplos *entrypoints* são especificados. +- **raiz do projeto**: o diretório do _entrypoint_ especificado para o Parcel, ou a raiz compartilhada (diretório pai em comum) quando múltiplos _entrypoints_ são especificados. - **raiz do pacote**: o diretório mais próximo da raiz do pacote em `node_modules`. ## Caminhos Absolutos @@ -47,7 +47,7 @@ Recomendamos ser explícito ao definir seus acrônimos, então por favor **espec ### Exportações denominadas com Javascript -Os mapeamentos de acrônimos se aplicam a muitos tipos de recursos e não oferecem suporte especificamente ao mapeamento de exportações denominadas com Javascript. Se você deseja mapear js chamado *exports* você pode fazer isso: +Os mapeamentos de acrônimos se aplicam a muitos tipos de recursos e não oferecem suporte especificamente ao mapeamento de exportações denominadas com Javascript. Se você deseja mapear js chamado _exports_ você pode fazer isso: ```json // package.json @@ -63,7 +63,7 @@ e re-exportando a exportação nomeada dentro do arquivo com acrônimo: ```js // electron-ipc.js -module.exports = require("electron").ipcRenderer; +module.exports = require('electron').ipcRenderer ``` ### Resolução ~ TypeScript @@ -82,9 +82,9 @@ TypeScript terá de saber sobre o seu uso da resolução de módulo com `~` ou m } ``` -### Resolução *Monorepo* +### Resolução _Monorepo_ -Estes são os usos aconselhados com *monorepos* até o momento: +Estes são os usos aconselhados com _monorepos_ até o momento: Uso recomendado: @@ -93,6 +93,6 @@ Uso recomendado: Uso não recomentado: -- **evite** utilizar `~` com *monorepos*. +- **evite** utilizar `~` com _monorepos_. -Se você é um usuário *monorepo* e gostaria de contribuir com essas recomendações, por favor, forneça repositórios de exemplo ao abrir *issues* para apoiar a discussão. +Se você é um usuário _monorepo_ e gostaria de contribuir com essas recomendações, por favor, forneça repositórios de exemplo ao abrir _issues_ para apoiar a discussão. diff --git a/src/i18n/pt/docs/openGL.md b/src/i18n/pt/docs/openGL.md index 7a15a6084..2e131c492 100644 --- a/src/i18n/pt/docs/openGL.md +++ b/src/i18n/pt/docs/openGL.md @@ -1,3 +1,3 @@ # OpenGL Shading Language (GLSL) -*Extensões suportadas: `glsl`, `vert`, `frag`* +_Extensões suportadas: `glsl`, `vert`, `frag`_ diff --git a/src/i18n/pt/docs/packagers.md b/src/i18n/pt/docs/packagers.md index 8a350e2ad..93985ae1b 100644 --- a/src/i18n/pt/docs/packagers.md +++ b/src/i18n/pt/docs/packagers.md @@ -5,22 +5,22 @@ No Parcel, um `Packager` combina múltiplos `Asset`s juntos em um pacote de saí ## Interface Packager ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // opcional. escreve no cabeçalho do arquivo, caso necessário. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // obrigatório. escreve o recurso no arquivo de saída. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // opcional. escreve o trailer do arquivo, caso necessário. - await this.dest.end(trailer); + await this.dest.end(trailer) } } @@ -32,8 +32,8 @@ module.exports = MyPackager Você pode registrar seu Packager com um bundler usando o método `addPackager`. Ele aceita um tipo de arquivo para se registrar e o caminho para seu módulo de pacote. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/pt/docs/plugins.md b/src/i18n/pt/docs/plugins.md index daf150cb0..3e2835852 100644 --- a/src/i18n/pt/docs/plugins.md +++ b/src/i18n/pt/docs/plugins.md @@ -9,10 +9,10 @@ Ao adicionar suporte para um novo formato de arquivo para o Parcel, você deve p Os plugins do Parcel são muito simples. Eles são simplesmente módulos que exportam uma única função, que é chamada pelo Parcel automaticamente durante a inicialização. A função recebe como entrada o objeto `Bundler` e pode realizar configurações, como registrar tipos de recursos e packagers. ```javascript -module.exports = function (bundler) { - bundler.addAssetType('ext', require.resolve('./MyAsset')); - bundler.addPackager('foo', require.resolve('./MyPackager')); -}; +module.exports = function(bundler) { + bundler.addAssetType('ext', require.resolve('./MyAsset')) + bundler.addPackager('foo', require.resolve('./MyPackager')) +} ``` Publique este pacote no npm usando o prefixo `parcel-plugin-` e ele será automaticamente detectado e carregado conforme descrito abaixo. diff --git a/src/i18n/pt/docs/pug.md b/src/i18n/pt/docs/pug.md index aec67866f..31544cad0 100644 --- a/src/i18n/pt/docs/pug.md +++ b/src/i18n/pt/docs/pug.md @@ -1,3 +1,3 @@ # Pug -*Extensões suportadas: `jade`, `pug`* +_Extensões suportadas: `jade`, `pug`_ diff --git a/src/i18n/pt/docs/reasonML.md b/src/i18n/pt/docs/reasonML.md index aec9918d6..f1ac2fd7d 100644 --- a/src/i18n/pt/docs/reasonML.md +++ b/src/i18n/pt/docs/reasonML.md @@ -1,10 +1,10 @@ # ReasonML -*Extensões suportadas: `ml`, `re`* +_Extensões suportadas: `ml`, `re`_ ## ReasonML/BuckleScript -[ReasonML](https://reasonml.github.io/) compila OCaml para JavaScript com a ajuda do [BuckleScript](https://bucklescript.github.io). Você pode utilizar ReasonML ao instalar as dependências e criar o arquivo `bsconfig.json`: +[ReasonML](https://reasonml.github.io/) compila OCaml para JavaScript com a ajuda do [BuckleScript](https://bucklescript.github.io). Você pode utilizar ReasonML ao instalar as dependências e criar o arquivo `bsconfig.json`: ```bash $ yarn add bs-platform --dev @@ -25,8 +25,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, @@ -52,7 +51,7 @@ print_endline("Hello World"); ### ReasonReact -[ReasonReact](https://reasonml.github.io/reason-react/) é um *bind* React para ReasonML. Você pode usar em conjunto com o Parcel também: +[ReasonReact](https://reasonml.github.io/reason-react/) é um _bind_ React para ReasonML. Você pode usar em conjunto com o Parcel também: ```bash $ yarn add react react-dom reason-react diff --git a/src/i18n/pt/docs/recipes.md b/src/i18n/pt/docs/recipes.md index 4ffaeb5b5..880988851 100644 --- a/src/i18n/pt/docs/recipes.md +++ b/src/i18n/pt/docs/recipes.md @@ -138,7 +138,7 @@ E então, no seu arquivo `index.html`, simplesmente referencie o seu arquivo `.t Feito! -### Compilando o arquivo `.ts` diretamente +### Compilando o arquivo `.ts` diretamente Adicione o script de inicialização ao `package.json` @@ -149,4 +149,4 @@ Adicione o script de inicialização ao `package.json` } ``` -Feito! 😄 O arquivo `.js` compilado pode ser encontrado dentro do diretório de distribuição. \ No newline at end of file +Feito! 😄 O arquivo `.js` compilado pode ser encontrado dentro do diretório de distribuição. diff --git a/src/i18n/pt/docs/rust.md b/src/i18n/pt/docs/rust.md index c9cf7216f..ab19be806 100644 --- a/src/i18n/pt/docs/rust.md +++ b/src/i18n/pt/docs/rust.md @@ -1,20 +1,20 @@ # Rust -*Extensões suportadas: `rs`* +_Extensões suportadas: `rs`_ [Rust](https://www.rust-lang.org/en-US/) é uma linguagem de programação de sistemas desenvolvida pela Mozilla, que oferece desempenho nativo com algumas características interessantes de memória e segurança de thread. Rust recentemente adicionado suporte para a compilação para WebAssembly, e agora o Parcel torna **super fácil** para começar com zero de configuração! -Agora você pode simplesmente importar arquivos `.rs` como qualquer outro tipo de arquivo no Parcel! Supondo que você tenha o [Rustup](https://rustup.rs) instalado, o Parcel **automaticamente cuida da instalação** das *toolchains* corretas, alvos e outros pré-requisitos de compilação. Ele funciona com projetos [Cargo](https://github.com/rust-lang/cargo), bem como arquivos *straight-up* do Rust, automaticamente rastreando suas dependências então **arquivos são assistidos** e reconstruídos sempre que você salvar, e muito mais! +Agora você pode simplesmente importar arquivos `.rs` como qualquer outro tipo de arquivo no Parcel! Supondo que você tenha o [Rustup](https://rustup.rs) instalado, o Parcel **automaticamente cuida da instalação** das _toolchains_ corretas, alvos e outros pré-requisitos de compilação. Ele funciona com projetos [Cargo](https://github.com/rust-lang/cargo), bem como arquivos _straight-up_ do Rust, automaticamente rastreando suas dependências então **arquivos são assistidos** e reconstruídos sempre que você salvar, e muito mais! Assim como com arquivos `.wasm`, arquivos `.rs` podem ser importados com as importações síncronas ou assíncronas. ```js // importação síncrona -import {add} from './add.rs'; -console.log(add(2, 3)); +import { add } from './add.rs' +console.log(add(2, 3)) // importação assíncrona -const {add} = await import('./add.rs'); -console.log(add(2, 3)); +const { add } = await import('./add.rs') +console.log(add(2, 3)) ``` No lado do Rust, você só precisa ter certeza de que os nomes de função não estão desconfiguradas e que são públicas. @@ -24,4 +24,4 @@ No lado do Rust, você só precisa ter certeza de que os nomes de função não pub fn add(a: i32, b: i32) -> i32 { return a + b } -``` \ No newline at end of file +``` diff --git a/src/i18n/pt/docs/scss.md b/src/i18n/pt/docs/scss.md index d0983dfae..62ca2303c 100644 --- a/src/i18n/pt/docs/scss.md +++ b/src/i18n/pt/docs/scss.md @@ -1,13 +1,17 @@ # SCSS -*Extensões suportadas: `sass`, `scss`* +_Extensões suportadas: `sass`, `scss`_ Compilação de SCSS requer o módulo `sass` (versão JS do `dart-sass`). Para instalá-lo com npm: + ```bash npm install sass ``` + Uma vez que o `sass` esteja instalado, você pode importar seus arquivos SCSS em arquivos JavaScript. + ```javascript import './custom.scss' ``` + Dependências nos arquivos SCSS podem ser utilizados com declarações `@import`. diff --git a/src/i18n/pt/docs/stylus.md b/src/i18n/pt/docs/stylus.md index 0dc8921f7..46b7d9f36 100644 --- a/src/i18n/pt/docs/stylus.md +++ b/src/i18n/pt/docs/stylus.md @@ -1,3 +1,3 @@ # Stylus -*Extensões suportadas: `stylus`* +_Extensões suportadas: `stylus`_ diff --git a/src/i18n/pt/docs/toml.md b/src/i18n/pt/docs/toml.md index b40c358a1..1f9e355d1 100644 --- a/src/i18n/pt/docs/toml.md +++ b/src/i18n/pt/docs/toml.md @@ -1,3 +1,3 @@ # TOML -*Extensões suportadas: `toml`* +_Extensões suportadas: `toml`_ diff --git a/src/i18n/pt/docs/transforms.md b/src/i18n/pt/docs/transforms.md index cf0ecc462..c954c7e94 100644 --- a/src/i18n/pt/docs/transforms.md +++ b/src/i18n/pt/docs/transforms.md @@ -2,4 +2,4 @@ Enquanto muitos empacotadores exigem que você instale e configure plugins para converter arquivos, o Parcel tem suporte de fábrica para a maioria dos conversores e transpiladores. Você pode converter JavaScript utilizando [Babel](https://babeljs.io), CSS utilizando [PostCSS](http://postcss.org), e HTML utilizando [PostHTML](https://github.com/posthtml/posthtml). Parcel utilizará esses conversores automaticamente se ele encontrar um arquivo de configuração em um módulo (por exemplo, `.babelrc` e `.postcssrc`). -Isso funciona mesmo em módulos de terceiros `node_modules`: se um arquivo de configuração é publicado como parte da distribuição do pacote, a conversão é feita automaticamente apenas para aquele módulo. Isso mantém o empacotamento rápido, já que apenas os módulos que precisam ser convertidos são processados. Isso também significa que você não precisa configurar manualmente as conversões para incluir e excluir determinados arquivos, ou saber como o código de outra pessoa foi criado para usá-lo em sua aplicação. \ No newline at end of file +Isso funciona mesmo em módulos de terceiros `node_modules`: se um arquivo de configuração é publicado como parte da distribuição do pacote, a conversão é feita automaticamente apenas para aquele módulo. Isso mantém o empacotamento rápido, já que apenas os módulos que precisam ser convertidos são processados. Isso também significa que você não precisa configurar manualmente as conversões para incluir e excluir determinados arquivos, ou saber como o código de outra pessoa foi criado para usá-lo em sua aplicação. diff --git a/src/i18n/pt/docs/typeScript.md b/src/i18n/pt/docs/typeScript.md index 002843c76..9573e657e 100644 --- a/src/i18n/pt/docs/typeScript.md +++ b/src/i18n/pt/docs/typeScript.md @@ -1,8 +1,8 @@ # TypeScript -*Extensões suportadas: `ts`, `tsx`* +_Extensões suportadas: `ts`, `tsx`_ -[TypeScript](https://www.typescriptlang.org/) é um superconjunto de JavaScript tipado que compila para JavaScript simples, que também suporta características mordernas do ES2015+. Conversões TypeScripe funcionam *out of the box*, sem a necessidade de nenhuma configuração adicional. +[TypeScript](https://www.typescriptlang.org/) é um superconjunto de JavaScript tipado que compila para JavaScript simples, que também suporta características mordernas do ES2015+. Conversões TypeScripe funcionam _out of the box_, sem a necessidade de nenhuma configuração adicional. ```html @@ -15,11 +15,11 @@ ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` diff --git a/src/i18n/pt/docs/vue.md b/src/i18n/pt/docs/vue.md index bfcf57895..81371d22d 100644 --- a/src/i18n/pt/docs/vue.md +++ b/src/i18n/pt/docs/vue.md @@ -1,3 +1,3 @@ # Vue -*Extensões suportadas: `vue`* +_Extensões suportadas: `vue`_ diff --git a/src/i18n/pt/docs/webAssembly.md b/src/i18n/pt/docs/webAssembly.md index d56a781f9..12bfedd18 100644 --- a/src/i18n/pt/docs/webAssembly.md +++ b/src/i18n/pt/docs/webAssembly.md @@ -1,6 +1,6 @@ # WebAssembly -*Extensões suportadas: `wasm`* +_Extensões suportadas: `wasm`_ [WebAssembly](https://webassembly.org) é uma tecnologia emergente, mas que terá um impacto enorme na Web em um futuro próximo. Agora apoiado por todos os principais navegadores da Web, bem como Node, WebAssembly permitirá uma diversidade de linguagens na Web, e não apenas aquelas que podem transpilar para JavaScript. @@ -10,13 +10,13 @@ Parcel torna **extremamente fácil** começar com WebAssembly. Supondo que você ```js // importação síncrona -import {add} from './add.wasm'; -console.log(add(2, 3)); +import { add } from './add.wasm' +console.log(add(2, 3)) // importação assíncrona -const {add} = await import('./add.wasm'); -console.log(add(2, 3)); +const { add } = await import('./add.wasm') +console.log(add(2, 3)) ``` Ao importar sincronicamente um arquivo `.wasm`, o Parcel gera automaticamente código extra para pré-carregar o arquivo antes de executar seu pacote JavaScript. Isso significa que o arquivo WebAssembly binário não é embutido em seu JavaScript como uma seqüência de caracteres, mas realmente servido como um arquivo binário separado como você esperaria. Desta forma, o seu código ainda funciona sincronicamente, mas Parcel cuida de carregar dependências para você. -Tudo isso é habilitado pelo suporte interno do Parcel para [carregadores de pacotes](https://github.com/parcel-bundler/parcel/pull/565), que são módulos de tempo de execução que sabem como carregar um formato de arquivo específico de forma assíncrona. Em versões anteriores, haviam carregadores de pacotes codificados para JavaScript e CSS, que habilitaram o suporte dinâmico de importação. No Parcel v1.5.0, isso é **completamente plugável** — você pode definir seus próprios carregadores de pacotes em plugins! Isso permitirá que muita funcionalidade legal no futuro para formatos binários personalizados como modelos binários de Glimmer, etc. Super animado para ver o que isso permite! \ No newline at end of file +Tudo isso é habilitado pelo suporte interno do Parcel para [carregadores de pacotes](https://github.com/parcel-bundler/parcel/pull/565), que são módulos de tempo de execução que sabem como carregar um formato de arquivo específico de forma assíncrona. Em versões anteriores, haviam carregadores de pacotes codificados para JavaScript e CSS, que habilitaram o suporte dinâmico de importação. No Parcel v1.5.0, isso é **completamente plugável** — você pode definir seus próprios carregadores de pacotes em plugins! Isso permitirá que muita funcionalidade legal no futuro para formatos binários personalizados como modelos binários de Glimmer, etc. Super animado para ver o que isso permite! diff --git a/src/i18n/pt/docs/webManifest.md b/src/i18n/pt/docs/webManifest.md index a7e2f420c..d3540e383 100644 --- a/src/i18n/pt/docs/webManifest.md +++ b/src/i18n/pt/docs/webManifest.md @@ -1,3 +1,3 @@ # WebManifest -*Extensões suportadas: `webmanifest`* +_Extensões suportadas: `webmanifest`_ diff --git a/src/i18n/pt/docs/yaml.md b/src/i18n/pt/docs/yaml.md index aa4cdafda..1a7d69277 100644 --- a/src/i18n/pt/docs/yaml.md +++ b/src/i18n/pt/docs/yaml.md @@ -1,3 +1,3 @@ # YAML -*Extensões suportadas: `yaml`, `yml`* +_Extensões suportadas: `yaml`, `yml`_ diff --git a/src/i18n/ru/docs/api.md b/src/i18n/ru/docs/api.md index 969e3cb53..ba67b5037 100644 --- a/src/i18n/ru/docs/api.md +++ b/src/i18n/ru/docs/api.md @@ -4,6 +4,7 @@ Вместо CLI вы также можете использовать API для инициализации упаковщика для более продвинутых вариантов использования (например, пользовательская обработка после каждой сборки). См. пример ниже, где объясняется каждая опция: + ```Javascript const Bundler = require('parcel-bundler'); const Path = require('path'); @@ -45,7 +46,8 @@ runBundle(); Список всех событий упаковщика -* `bundled` вызывается после того, как Parcel успешно завершил сборку, основной [бандл](#bundle) передаётся в коллбэк +- `bundled` вызывается после того, как Parcel успешно завершил сборку, основной [бандл](#bundle) передаётся в коллбэк + ```Javascript const bundler = new Bundler(...); bundler.on('bundled', (bundle) => { @@ -53,7 +55,8 @@ bundler.on('bundled', (bundle) => { }); ``` -* `buildEnd` вызывается после каждой сборки, он также вызывается в случае ошибки +- `buildEnd` вызывается после каждой сборки, он также вызывается в случае ошибки + ```Javascript const bundler = new Bundler(...); bundler.on('buildEnd', () => { @@ -67,20 +70,19 @@ bundler.on('buildEnd', () => { #### Properties -* `type`: Тип ресурсов, которые он содержит (например, js, css, map, ...) -* `name`: Имя бандла (сгенерированное с помощью `Asset.generateBundleName()` `entryAsset`) -* `parentBundle`: Родительский бандл, null в случае входного бандла -* `entryAsset`: Точка входа бандла, используется для генерации имени сборка ресурсов. -* `assets`: Набор (`Set`) всех ресурсов внутри бандла -* `childBundles`: Набор (`Set`) всех дочерних бандлов -* `siblingBundles`: Набор (`Set`) всех родственных бандлов -* `siblingBundlesMap`: Карта (`Map`) всех дочерних бандлов -* `offsets`: Карта (`Map`) всех местоположений ресурсов внутри бандла, используемых для генерации всех точных source maps +- `type`: Тип ресурсов, которые он содержит (например, js, css, map, ...) +- `name`: Имя бандла (сгенерированное с помощью `Asset.generateBundleName()` `entryAsset`) +- `parentBundle`: Родительский бандл, null в случае входного бандла +- `entryAsset`: Точка входа бандла, используется для генерации имени сборка ресурсов. +- `assets`: Набор (`Set`) всех ресурсов внутри бандла +- `childBundles`: Набор (`Set`) всех дочерних бандлов +- `siblingBundles`: Набор (`Set`) всех родственных бандлов +- `siblingBundlesMap`: Карта (`Map`) всех дочерних бандлов +- `offsets`: Карта (`Map`) всех местоположений ресурсов внутри бандла, используемых для генерации всех точных source maps #### Tree -Бандл (`Bundle`) содержат родительский бандл (`parentBundle`), дочерний бандл (`childBundles`) и родственный бандл (`siblingBundles`), все эти свойства вместе создают быстрое дерерво бандлов для итерации. - +Бандл (`Bundle`) содержат родительский бандл (`parentBundle`), дочерний бандл (`childBundles`) и родственный бандл (`siblingBundles`), все эти свойства вместе создают быстрое дерерво бандлов для итерации. Очень простой пример дерева ресурсов и его сгенерированного дерево бандлов @@ -106,7 +108,7 @@ index.html `test.js` добавляется к ресурсам бандла `index.js`, поскольку он имеет тот же тип, что и `index.js` -`test.txt` создаёт новый бандл и добавляется как дочерний бандл `index.js`, поскольку это другой тип ресурса, чем `index.js` +`test.txt` создаёт новый бандл и добавляется как дочерний бандл `index.js`, поскольку это другой тип ресурса, чем `index.js` `index.css` ничего не требует и, следовательно, содержит только входный ресурс. @@ -124,6 +126,7 @@ index.html Мидлвар (middleware) может использоваться для подключения к HTTP-серверу (например, `express` или node `http`). Пример использования мидлвар Parcel с express + ```Javascript const Bundler = require('parcel-bundler'); const app = require('express')(); diff --git a/src/i18n/ru/docs/asset_types.md b/src/i18n/ru/docs/asset_types.md index b28be5885..cbde182e3 100644 --- a/src/i18n/ru/docs/asset_types.md +++ b/src/i18n/ru/docs/asset_types.md @@ -7,15 +7,14 @@ ## Интерфейс ресурса ```javascript - -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // устанавливаем основной тип вывода. + type = 'foo' // устанавливаем основной тип вывода. async parse(code) { // разбор кода в AST. - return ast; + return ast } async pretransform() { @@ -24,11 +23,11 @@ class MyAsset extends Asset { collectDependencies() { // анализ зависимостей. - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { - // преобразовать после сбора зависимостей. (опционально) + // преобразовать после сбора зависимостей. (опционально) } async generate() { @@ -44,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', //альтернативное исполнение для размещения в JS-бандле, если необходимо sourceMap } - ]; + ] } async postProcess(generated) { @@ -59,8 +58,8 @@ class MyAsset extends Asset { Вы можете зарегистрировать свой тип ресурса, используя метод `addAssetType`. Он принимает расширение файла для регистрации и путь к модулю типа ресурса. Это путь, а не фактический объект, чтобы он мог передаваться рабочим процессам. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/ru/docs/assets.md b/src/i18n/ru/docs/assets.md index c65b6dd7f..7132a4295 100644 --- a/src/i18n/ru/docs/assets.md +++ b/src/i18n/ru/docs/assets.md @@ -8,35 +8,35 @@ Parcel основан на ресурсах. Ресурсы могут пред ```javascript // Импортировать модуль с использованием синтаксиса CommonJS -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // Импорт модуля с использованием синтаксиса импорта ES6 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` Вы также можете импортировать не JavaScript из JavaScript-файла, например CSS или даже файл изображения. Когда вы импортируете один из этих файлов, он не встраивается в другие бандлы, как это происходит в некоторых других упаковщиках. Вместо этого он помещается в отдельный бандл (например CSS-файл) вместе со всеми его зависимостями. Когда вы используете [CSS Modules](https://github.com/css-modules/css-modules), экспортированные классы помещаются в бандл JavaScript. Другие типы ресурсов экспортируют URL-адрес в выходной файл в бандле JavaScript, чтобы вы могли ссылаться на них в своем коде. ```javascript // Импортировать файл CSS -import './test.css'; +import './test.css' // Импортировать файл CSS с помощью CSS-модулей -import classNames from './test.css'; +import classNames from './test.css' // Импортировать URL-адрес в файл изображения -import imageURL from './test.png'; +import imageURL from './test.png' ``` Если вы хотите встроить файл в бандл JavaScript вместо ссылки по его URL-адресу, вы можете использовать для этого API Node.js `fs.readFileSync`. URL-адрес должен быть статически анализируемым, то есть он не может иметь никаких переменных (кроме `__dirname` и `__filename`). ```javascript -import fs from 'fs'; +import fs from 'fs' // Чтение содержимого в виде строки -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // Чтение содержимого в качестве Buffer -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') ``` ## CSS diff --git a/src/i18n/ru/docs/cli.md b/src/i18n/ru/docs/cli.md index 3b49beb1d..c4d232956 100644 --- a/src/i18n/ru/docs/cli.md +++ b/src/i18n/ru/docs/cli.md @@ -124,12 +124,12 @@ parcel serve entry.js --port 1111 parcel entry.js --log-level 1 ``` -| Уровень логирования | Эффект | -|--- |--- | -| 0 | Логирование отключено | -| 1 | Логировать только ошибки | -| 2 | Логировать только ошибки и предупреждения | -| 3 | Логировать всё | +| Уровень логирования | Эффект | +| ------------------- | ----------------------------------------- | +| 0 | Логирование отключено | +| 1 | Логировать только ошибки | +| 2 | Логировать только ошибки и предупреждения | +| 3 | Логировать всё | ### Имя хоста для HMR diff --git a/src/i18n/ru/docs/code_splitting.md b/src/i18n/ru/docs/code_splitting.md index 1f3dfb9f0..5f2680287 100644 --- a/src/i18n/ru/docs/code_splitting.md +++ b/src/i18n/ru/docs/code_splitting.md @@ -14,18 +14,18 @@ export function render() { ``` ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // Отобразить страницу - page.render(); -}); + page.render() +}) ``` Так как `import()` возвращает Promise, вы можете использовать синтаксис async/await. Вероятно, вам нужно настроить Babel для преобразования синтаксиса, пока он более широко не поддерживается браузерами. ```javascript -const page = await import('./pages/about'); +const page = await import('./pages/about') // Отобразить страницу -page.render(); +page.render() ``` Динамический импорт также лениво загружается в Parcel, поэтому вы можете поместить все свои вызовы `import()` вверху файла, а дочерние бандлы не будут загружаться до тех пор, пока они не будут использованы. В следующем примере показано, как можно лениво загружать подстраницы приложения динамически. @@ -36,12 +36,12 @@ page.render(); const pages = { about: import('./pages/about'), blog: import('./pages/blog') -}; +} async function renderPage(name) { // Лениво загрузить запрошенную страницу. - const page = await pages[name]; - return page.render(); + const page = await pages[name] + return page.render() } ``` @@ -52,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +import 'babel-polyfill' +import './app' ``` Прочитайте документацию [babel-polyfill](http://babeljs.io/docs/usage/polyfill) и [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime). diff --git a/src/i18n/ru/docs/getting_started.md b/src/i18n/ru/docs/getting_started.md index 5a7aecc80..568fb49d8 100644 --- a/src/i18n/ru/docs/getting_started.md +++ b/src/i18n/ru/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel — это упаковщик для веб-приложений Сначала установите Parcel с помощью Yarn или npm: Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ npm install -g parcel-bundler ```bash yarn init -y ``` -или + +или + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Parcel может принимать любой тип файла в качес ``` ```javascript -console.log("Привет, Мир!"); +console.log('Привет, Мир!') ``` Parcel имеет встроенный сервер разработки, который будет автоматически пересобирать ваше приложение, так как поддерживает [горячую замену модуля](hmr.html) для увеличения скорости разработки. Просто выполните команду: diff --git a/src/i18n/ru/docs/hmr.md b/src/i18n/ru/docs/hmr.md index 9ea8cdb2a..cce63f204 100644 --- a/src/i18n/ru/docs/hmr.md +++ b/src/i18n/ru/docs/hmr.md @@ -8,21 +8,23 @@ ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // модуль будет заменен. - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // модуль или одна из его зависимостей была только что обновлена. - }); + }) } ``` + ## Безопасная запись + У некоторых текстовых редакторов и IDE есть возможность, называемая `safe write` (безопасная запись), которая в основном предотвращает потерю данных, делая копию файла и переименовывая его при сохранении. При использовании горячей перезагрузки эта возможность блокирует автоматическое обнаружение обновлений файлов, поэтому для отключения безопасной записи используйте подходящий вам вариант: -* `Sublime Text 3` добавьте `atomic_save: "false"` в пользовательские настройки. -* `IntelliJ` воспользуйтесь поиском и найдите в настройках (preferences) "safe write" и отключите её. -* `Vim` добавьте `:set backupcopy=yes` к вашим настройкам. -* `WebStorm` снимите галочку `Use "safe write"`, перейдя в Preferences > Appearance & Behavior > System Settings. +- `Sublime Text 3` добавьте `atomic_save: "false"` в пользовательские настройки. +- `IntelliJ` воспользуйтесь поиском и найдите в настройках (preferences) "safe write" и отключите её. +- `Vim` добавьте `:set backupcopy=yes` к вашим настройкам. +- `WebStorm` снимите галочку `Use "safe write"`, перейдя в Preferences > Appearance & Behavior > System Settings. diff --git a/src/i18n/ru/docs/how_it_works.md b/src/i18n/ru/docs/how_it_works.md index 4d028ddc1..f25a683aa 100644 --- a/src/i18n/ru/docs/how_it_works.md +++ b/src/i18n/ru/docs/how_it_works.md @@ -16,4 +16,4 @@ Parcel принимает в качестве входных данных оди ### 3. Упаковка -После того, как построено дерево бандлов, каждый бандл записывается в файл [упаковщиком](packagers.html), специфичным для данного типа файла. Упаковщики знают, как объединить код из каждого ресурса в конечный файл, который будет загружен браузером. +После того, как построено дерево бандлов, каждый бандл записывается в файл [упаковщиком](packagers.html), специфичным для данного типа файла. Упаковщики знают, как объединить код из каждого ресурса в конечный файл, который будет загружен браузером. diff --git a/src/i18n/ru/docs/meta.json b/src/i18n/ru/docs/meta.json index 1e51c307d..90e78481c 100644 --- a/src/i18n/ru/docs/meta.json +++ b/src/i18n/ru/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "ru" } -} \ No newline at end of file +} diff --git a/src/i18n/ru/docs/packagers.md b/src/i18n/ru/docs/packagers.md index d5b3f0b42..3379753e8 100644 --- a/src/i18n/ru/docs/packagers.md +++ b/src/i18n/ru/docs/packagers.md @@ -5,22 +5,22 @@ ## Интерфейс упаковщика ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // (опционально) запись заголовока файла, если это необходимо. - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // запись ресурса в выходной файл. - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // (опционально) при необходимости напишите окончание файла. - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MyPackager extends Packager { Вы можете зарегистрировать упаковщик с помощью метода `addPackager`. Он принимает тип файла для регистрации и путь к вашему модулю упаковщика. ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/ru/docs/plugins.md b/src/i18n/ru/docs/plugins.md index 51f40b340..a6f213d06 100644 --- a/src/i18n/ru/docs/plugins.md +++ b/src/i18n/ru/docs/plugins.md @@ -9,10 +9,10 @@ Parcel использует несколько иной подход из мно Плагины для Parcel очень просты. Это просто модули, которые экспортируют одну функцию, которая автоматически вызывается Parcel во время инициализации. Функция получает объект `Bundler` в качестве входных данных и может выполнять такую настройку, как регистрация типов ресурсов и упаковщиков. ```javascript -module.exports = function (bundler) { - bundler.addAssetType('ext', require.resolve('./MyAsset')); - bundler.addPackager('foo', require.resolve('./MyPackager')); -}; +module.exports = function(bundler) { + bundler.addAssetType('ext', require.resolve('./MyAsset')) + bundler.addPackager('foo', require.resolve('./MyPackager')) +} ``` Опубликуйте этот пакет на npm, используя префикс `parcel-plugin-`, и он будет автоматически обнаружен и загружен, как описано ниже. diff --git a/src/i18n/ru/docs/production.md b/src/i18n/ru/docs/production.md index efde8d102..51c570a71 100644 --- a/src/i18n/ru/docs/production.md +++ b/src/i18n/ru/docs/production.md @@ -8,4 +8,4 @@ parcel build entry.js Это отключает режим просмотра и горячую замену модулей и ваше приложение будет собрано только один раз и позволяет минимизировать все выходные бандлы для уменьшения размера файла. Минификаторы, используемые Parcel: [terser](https://github.com/fabiosantoscode/terser) для JavaScript, [cssnano](http://cssnano.co) для CSS и [htmlnano](https://github.com/posthtml/htmlnano) для HTML. -Включение режима продакшена также устанавливает переменную среды `NODE_ENV=production`. Большие библиотеки, такие как React, имеют только функциональность для отладки, которые отключается через эту переменную среды, что приводит к меньшим и быстрым сборкам для продакшена. \ No newline at end of file +Включение режима продакшена также устанавливает переменную среды `NODE_ENV=production`. Большие библиотеки, такие как React, имеют только функциональность для отладки, которые отключается через эту переменную среды, что приводит к меньшим и быстрым сборкам для продакшена. diff --git a/src/i18n/ru/docs/transforms.md b/src/i18n/ru/docs/transforms.md index 200527add..507ca5ecb 100644 --- a/src/i18n/ru/docs/transforms.md +++ b/src/i18n/ru/docs/transforms.md @@ -86,7 +86,7 @@ yarn add posthtml-img-autosize ## TypeScript -[TypeScript](https://www.typescriptlang.org/) - типизированное надмножество JavaScript, которое компилирует код до обычного JavaScript, который также поддерживает современные возможности ES2015+. Преобразование TypeScript работает без всякой дополнительной настройки. +[TypeScript](https://www.typescriptlang.org/) - типизированное надмножество JavaScript, которое компилирует код до обычного JavaScript, который также поддерживает современные возможности ES2015+. Преобразование TypeScript работает без всякой дополнительной настройки. ```html @@ -99,13 +99,13 @@ yarn add posthtml-img-autosize ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` ## ReasonML/BuckleScript @@ -131,8 +131,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, diff --git a/src/i18n/uk/docs/api.md b/src/i18n/uk/docs/api.md index d04f9d9ec..939513621 100644 --- a/src/i18n/uk/docs/api.md +++ b/src/i18n/uk/docs/api.md @@ -4,6 +4,7 @@ Замість CLI ви також можете використовувати API для ініціалізації пакувальника для більш просунутих варіантів використання (наприклад, для користувача обробка після кожної збірки). Див. Приклад нижче, де пояснюється кожна опція: + ```Javascript const Bundler = require('parcel-bundler'); const Path = require('path'); @@ -45,7 +46,8 @@ runBundle(); Список усіх подій пакувальника -* `Bundled` викликається після того, як Parcel успішно завершив збірку, основний [бандл](#bundle) передається в коллбек +- `Bundled` викликається після того, як Parcel успішно завершив збірку, основний [бандл](#bundle) передається в коллбек + ```Javascript const bundler = new Bundler (...); bundler.on ('bundled', (bundle) => { @@ -53,7 +55,8 @@ bundler.on ('bundled', (bundle) => { }); ``` -* `BuildEnd` викликається після кожної збірки, він також викликається в разі помилки +- `BuildEnd` викликається після кожної збірки, він також викликається в разі помилки + ```Javascript const bundler = new Bundler (...); bundler.on ('buildEnd', () => { @@ -67,20 +70,19 @@ bundler.on ('buildEnd', () => { #### Properties -* `Type`: Тип ресурсів, які він містить (наприклад, js, css, map, ...) -* `Name`: Ім'я бандла (згенеровані за допомогою` Asset.generateBundleName () `` entryAsset`) -* `ParentBundle`: Батьківський бандл, null в разі вхідного бандла -* `EntryAsset`: Точка входу бандла, використовується для генерації імені збірки ресурсів. -* `Assets`: Набір (` Set`) всіх ресурсів всередині бандла -* `ChildBundles`: Набір (` Set`) всіх дочірніх бандлів -* `SiblingBundles`: Набір (` Set`) всіх споріднених бандлів -* `SiblingBundlesMap`: Карта (` Map `) всіх дочірніх бандлів -* `Offsets`: Карта (` Map `) всіх місць розташування ресурсів всередині бандла, використовуваних для генерації всіх точних source maps +- `Type`: Тип ресурсів, які він містить (наприклад, js, css, map, ...) +- `Name`: Ім'я бандла (згенеровані за допомогою` Asset.generateBundleName () `` entryAsset `) +- `ParentBundle`: Батьківський бандл, null в разі вхідного бандла +- `EntryAsset`: Точка входу бандла, використовується для генерації імені збірки ресурсів. +- `Assets`: Набір (`Set`) всіх ресурсів всередині бандла +- `ChildBundles`: Набір (`Set`) всіх дочірніх бандлів +- `SiblingBundles`: Набір (`Set`) всіх споріднених бандлів +- `SiblingBundlesMap`: Карта (`Map `) всіх дочірніх бандлів +- `Offsets`: Карта (`Map `) всіх місць розташування ресурсів всередині бандла, використовуваних для генерації всіх точних source maps #### Tree -Бандл (`Bundle`) містить батьківський бандл (` parentBundle`), дочірній бандл (`childBundles`) і споріднений бандл (` siblingBundles`), всі ці властивості разом створюють швидке дерерво бандлів для ітерації. - +Бандл (`Bundle`) містить батьківський бандл (`parentBundle`), дочірній бандл (`childBundles`) і споріднений бандл (`siblingBundles`), всі ці властивості разом створюють швидке дерерво бандлів для ітерації. Дуже простий приклад дерева ресурсів і його згенерованого дерева бандлів @@ -100,17 +102,17 @@ index.html ##### Bundle Tree: -`Index.html` використовується як вхідний ресурс для основного бандла, цей основний бандл створює два дочірні бандли: один для` index.js` і другий для `index.css`, тому що обидва вони відрізняються від типу` html`. +`Index.html` використовується як вхідний ресурс для основного бандла, цей основний бандл створює два дочірні бандли: один для`index.js` і другий для `index.css`, тому що обидва вони відрізняються від типу`html`. -`Index.js` вимагає два файли,` test.js` і `test.txt`. +`Index.js` вимагає два файли,`test.js` і `test.txt`. -`Test.js` додається до ресурсів бандла` index.js`, оскільки він має той же тип, що і `index.js` +`Test.js` додається до ресурсів бандла`index.js`, оскільки він має той же тип, що і `index.js` -`Test.txt` створює новий бандл і додається як дочірній бандл` index.js`, оскільки це інший тип ресурсу, ніж `index.js` +`Test.txt` створює новий бандл і додається як дочірній бандл`index.js`, оскільки це інший тип ресурсу, ніж `index.js` `Index.css` нічого не вимагає, отже, містить тільки вхідні ресурси. -`Index.css` і` index.js` - споріднені бандли для один одного, оскільки вони мають один і той же батьківський елемент. +`Index.css` і`index.js` - споріднені бандли для один одного, оскільки вони мають один і той же батьківський елемент. ```Text index.html @@ -121,9 +123,10 @@ index.html ### Мідлвар -Мідлвар (middleware) може використовуватися для підключення до HTTP-сервера (наприклад, `express` або node` http`). +Мідлвар (middleware) може використовуватися для підключення до HTTP-сервера (наприклад, `express` або node`http`). Приклад використання мідлвар Parcel з express + ```Javascript const Bundler = require ( 'parcel-bundler'); const app = require ( 'express') (); diff --git a/src/i18n/uk/docs/asset_types.md b/src/i18n/uk/docs/asset_types.md index 76dbdd5c9..972b4516e 100644 --- a/src/i18n/uk/docs/asset_types.md +++ b/src/i18n/uk/docs/asset_types.md @@ -7,7 +7,6 @@ ## Інтерфейс ресурсу ```Javascript - const {Asset} = require ('parcel-bundler'); class MyAsset extends Asset { @@ -63,4 +62,4 @@ const Bundler = require ('parcel-bundler'); let bundler = new Bundler ( 'input.js'); bundler.addAssetType ('.ext', require.resolve ('./MyAsset')); -``` \ No newline at end of file +``` diff --git a/src/i18n/uk/docs/assets.md b/src/i18n/uk/docs/assets.md index cedf2f244..d81ceb8eb 100644 --- a/src/i18n/uk/docs/assets.md +++ b/src/i18n/uk/docs/assets.md @@ -41,7 +41,7 @@ const buffer = fs.readFileSync(__dirname + '/test.png'); ## CSS -Ресурси CSS можуть бути імпортовані з файлу JavaScript або HTML і можуть містити залежності, на які посилається синтаксис `@import`, а також посилання на зображення, шрифти і так далі через` url()`. Інші імпортовані файли CSS за допомогою `@import`, вбудовуються в один і той же бандл CSS, посилання` url() `переписуються на їх вихідні імена файлів. Всі імена файлів повинні ставитися до поточного файлу CSS. +Ресурси CSS можуть бути імпортовані з файлу JavaScript або HTML і можуть містити залежності, на які посилається синтаксис `@import`, а також посилання на зображення, шрифти і так далі через`url()`. Інші імпортовані файли CSS за допомогою `@import`, вбудовуються в один і той же бандл CSS, посилання`url()`переписуються на їх вихідні імена файлів. Всі імена файлів повинні ставитися до поточного файлу CSS. ```Css /* Імпортувати інший файл CSS */ @@ -87,4 +87,4 @@ import './custom.scss'    -``` \ No newline at end of file +``` diff --git a/src/i18n/uk/docs/cli.md b/src/i18n/uk/docs/cli.md index a9ef20134..0873a6fff 100644 --- a/src/i18n/uk/docs/cli.md +++ b/src/i18n/uk/docs/cli.md @@ -21,7 +21,7 @@ parcel build index.html ### Watch -Команда `watch` схожа на` serve`, з основною відмінністю: вона не запускає сервер. +Команда `watch` схожа на`serve`, з основною відмінністю: вона не запускає сервер. ```Bash parcel watch index.html @@ -49,7 +49,7 @@ parcel --version Значення за замовчуванням: "dist" -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --out-dir build/output @@ -68,7 +68,7 @@ root Значення за замовчуванням: [аналогічно зазначеному в опції --out-dir](#output-directory) -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel entry.js --public-url ./dist/ @@ -86,19 +86,19 @@ parcel entry.js --public-url ./dist/ Значення за замовчуванням: browser -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --target node ``` -Можливі цілі: `node`,` browser`, `electron` +Можливі цілі: `node`,`browser`, `electron` ### Каталог кешування Значення за замовчуванням: ".cache" -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --cache-dir build/cache @@ -118,24 +118,24 @@ parcel serve entry.js --port 1111 Значення за замовчуванням: 3 -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel entry.js --log-level 1 ``` -| Рівень логування | Ефект | -| --- | --- | -| 0 | Логування відключено | -| 1 | Логувати тільки помилки | -| 2 | Логувати тільки помилки і попередження | -| 3 | Логувати все | +| Рівень логування | Ефект | +| ---------------- | -------------------------------------- | +| 0 | Логування відключено | +| 1 | Логувати тільки помилки | +| 2 | Логувати тільки помилки і попередження | +| 3 | Логувати все | ### Ім'я хоста для HMR Значення за замовчуванням: `location.hostname` поточного вікна -Доступно для: `serve`,` watch` +Доступно для: `serve`,`watch` ```Bash parcel entry.js --hmr-hostname parceljs.org @@ -145,7 +145,7 @@ parcel entry.js --hmr-hostname parceljs.org Значення за замовчуванням: Випадковий доступний порт -Доступно для: `serve`,` watch` +Доступно для: `serve`,`watch` ```Bash parcel entry.js --hmr-port 8080 @@ -155,7 +155,7 @@ parcel entry.js --hmr-port 8080 Значення за замовчуванням: вихідне ім'я файлу -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --out-file output.html @@ -177,7 +177,7 @@ parcel build entry.js --detailed-report Значення за замовчуванням: https відключений -Доступно для: `serve`,` watch` (працює на HTTPS для підключень HMR) +Доступно для: `serve`,`watch` (працює на HTTPS для підключень HMR) ```Bash parcel build entry.js --https @@ -189,7 +189,7 @@ parcel build entry.js --https Значення за замовчуванням: https відключений -Доступно для: `serve`,` watch` +Доступно для: `serve`,`watch` ```Bash parcel entry.js --cert certificate.cert --key private.key @@ -209,7 +209,7 @@ parcel entry.js --open Значення за замовчуванням: source-maps включені -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --no-source-maps @@ -219,7 +219,7 @@ parcel build entry.js --no-source-maps Значення за замовчуванням: установка включена -Доступно для: `serve`,` watch` +Доступно для: `serve`,`watch` ```Bash parcel entry.js --no-autoinstall @@ -229,7 +229,7 @@ parcel entry.js --no-autoinstall Значення за замовчуванням: HMR включений -Доступно для: `serve`,` watch` +Доступно для: `serve`,`watch` ```Bash parcel entry.js --no-hmr @@ -249,7 +249,7 @@ parcel build entry.js --no-minify Значення за замовчуванням: кешування включено -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel build entry.js --no-cache @@ -259,7 +259,7 @@ parcel build entry.js --no-cache Значення за замовчуванням: відключено -Доступно для: `serve`,` watch`, `build` +Доступно для: `serve`,`watch`, `build` ```Bash parcel serve entry.js --global myvariable @@ -275,4 +275,4 @@ parcel serve entry.js --global myvariable parcel serve entry.js --experimental-scope-hoisting ``` -Для отримання додаткової інформації дивіться [розділ Tree Shaking](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) в записі Девона Говетта (Devon Govett) про Parcel 1.9. \ No newline at end of file +Для отримання додаткової інформації дивіться [розділ Tree Shaking](https://medium.com/@devongovett/parcel-v1-9-0-tree-shaking-2x-faster-watcher-and-more-87f2e1a70f79#4ed3) в записі Девона Говетта (Devon Govett) про Parcel 1.9. diff --git a/src/i18n/uk/docs/code_splitting.md b/src/i18n/uk/docs/code_splitting.md index f0cc8d579..2d9a868e0 100644 --- a/src/i18n/uk/docs/code_splitting.md +++ b/src/i18n/uk/docs/code_splitting.md @@ -45,7 +45,7 @@ async function renderPage(name) { } ``` -** Примітка: ** Якщо ви хочете використовувати async / wait в браузерах, які не підтримують його, не забудьте включити `babel-polyfill` в вашому додатку або` babel-runtime` + `babel-plugin-transform-runtime` в бібліотеках. +** Примітка: ** Якщо ви хочете використовувати async / wait в браузерах, які не підтримують його, не забудьте включити `babel-polyfill` в вашому додатку або`babel-runtime` + `babel-plugin-transform-runtime` в бібліотеках. ```Bash yarn add babel-polyfill @@ -56,4 +56,4 @@ import "babel-polyfill"; import "./app"; ``` -Прочитайте документацію [babel-polyfill](http://babeljs.io/docs/usage/polyfill) і [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime). \ No newline at end of file +Прочитайте документацію [babel-polyfill](http://babeljs.io/docs/usage/polyfill) і [babel-runtime](http://babeljs.io/docs/plugins/transform-runtime). diff --git a/src/i18n/uk/docs/env.md b/src/i18n/uk/docs/env.md index 59c3091e5..a6f406119 100644 --- a/src/i18n/uk/docs/env.md +++ b/src/i18n/uk/docs/env.md @@ -2,11 +2,11 @@ Parcel використовує [dotenv](https://github.com/motdotla/dotenv) щоб підтримувати змінні середовища завантаження з файлів `.env`. -Файли `.env` повинні зберігатися поряд з пакунком` package.json`, який містить вашу `parcel-bundler` залежність. +Файли `.env` повинні зберігатися поряд з пакунком`package.json`, який містить вашу `parcel-bundler` залежність. -Parcel завантажує файли `.env` з цими конкретними іменами для таких значень` NODE_ENV`: +Parcel завантажує файли `.env` з цими конкретними іменами для таких значень`NODE_ENV`: -| коректна `.env` назва | `NODE_ENV=\*` | `NODE_ENV=test` | +| коректна `.env` назва | `NODE_ENV=\*` | `NODE_ENV=test` | | ------------------------ | ------------- | --------------- | | `.env` | ✔️ | ✔️ | | `.env.local` | ✔️ | ✖️ | diff --git a/src/i18n/uk/docs/getting_started.md b/src/i18n/uk/docs/getting_started.md index 513947f4e..cf5eb014e 100644 --- a/src/i18n/uk/docs/getting_started.md +++ b/src/i18n/uk/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel  — це пакувальник для веб-додатків Спочатку встановіть Parcel за допомогою Yarn або npm: Yarn: + ```Bash yarn global add parcel-bundler ``` npm: + ```Bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ npm install -g parcel-bundler ```Bash yarn init -y ``` + або + ```Bash npm init -y ``` @@ -54,4 +58,4 @@ parcel index.html parcel watch index.html ``` -Коли ви готові для збірки в продакшені, режим `build` НЕ буде відстежувати зміни файлів і збирає додаток тільки один раз. Дивіться подробиці в розділі [Робота в продакшені](production.html). \ No newline at end of file +Коли ви готові для збірки в продакшені, режим `build` НЕ буде відстежувати зміни файлів і збирає додаток тільки один раз. Дивіться подробиці в розділі [Робота в продакшені](production.html). diff --git a/src/i18n/uk/docs/hmr.md b/src/i18n/uk/docs/hmr.md index ad4472b98..7f72a0be6 100644 --- a/src/i18n/uk/docs/hmr.md +++ b/src/i18n/uk/docs/hmr.md @@ -4,7 +4,7 @@ Коли ви зберігаєте файли, Parcel відновлює зміни і відправляє оновлення всім працюючим клієнтам, що містить новий код. Потім новий код замінює стару версію і повторно оцінюється разом з усіма батьками. Ви можете підключитися до цього процесу, використовуючи API `module.hot`, який може повідомити ваш код, коли модуль буде видалений, або коли приходить нова версія. Такі проекти, як [react-hot-loader](https://github.com/gaearon/react-hot-loader), можуть допомогти в цьому процесі і працюють з Parcel з коробки. -Є два методи, які потрібно знати: `module.hot.accept` і` module.hot.dispose`. Ви викликаєте `module.hot.accept` з функцією зворотнього виклику, яка виконується при оновленні цього модуля або будь-яких його залежностей. `Module.hot.dispose` приймає зворотній виклик, який викликається, коли цей модуль буде замінений. +Є два методи, які потрібно знати: `module.hot.accept` і`module.hot.dispose`. Ви викликаєте `module.hot.accept` з функцією зворотнього виклику, яка виконується при оновленні цього модуля або будь-яких його залежностей. `Module.hot.dispose` приймає зворотній виклик, який викликається, коли цей модуль буде замінений. ```Javascript if (module.hot) { @@ -17,12 +17,14 @@ if (module.hot) {   }); } ``` + ## Безпечний запис + У деяких текстових редакторах та IDE є можливість, так звана `safe write` (безпечний запис), яка в основному запобігає втраті даних, роблячи копію файлу та перейменовуючи його при збереженні. При використанні гарячої перезавантаження ця можливість блокує автоматичне виявлення оновлень файлів, тому для відключення безпечного запису використовуйте відповідний вам варіант: -* `Sublime Text 3` додайте` atomic_save: "false" `в призначені для користувача налаштування. -* `IntelliJ` скористайтеся пошуком і знайдіть в налаштуваннях (preferences)` safe write` і відключіть її. -* `Vim` додайте`: set backupcopy = yes` до ваших налаштувань. -* `WebStorm` зніміть галочку` Use "safe write" `, перейшовши в Preferences> Appearance & Behavior> System Settings. \ No newline at end of file +- `Sublime Text 3` додайте`atomic_save: "false"`в призначені для користувача налаштування. +- `IntelliJ` скористайтеся пошуком і знайдіть в налаштуваннях (preferences)`safe write` і відключіть її. +- `Vim` додайте`: set backupcopy = yes` до ваших налаштувань. +- `WebStorm` зніміть галочку`Use "safe write"`, перейшовши в Preferences> Appearance & Behavior> System Settings. diff --git a/src/i18n/uk/docs/how_it_works.md b/src/i18n/uk/docs/how_it_works.md index a94fdb5af..adb0b2104 100644 --- a/src/i18n/uk/docs/how_it_works.md +++ b/src/i18n/uk/docs/how_it_works.md @@ -16,4 +16,4 @@ Parcel приймає в якості вхідних даних один еле ### 3. Упаковка -Після того, як побудовано дерево бандлів, кожен бандл записується в файл [пакувальником](packagers.html), специфічним для даного типу файлу. Пакувальники знають, як об'єднати код з кожного ресурсу в кінцевий файл, який буде завантажений браузером. \ No newline at end of file +Після того, як побудовано дерево бандлів, кожен бандл записується в файл [пакувальником](packagers.html), специфічним для даного типу файлу. Пакувальники знають, як об'єднати код з кожного ресурсу в кінцевий файл, який буде завантажений браузером. diff --git a/src/i18n/uk/docs/meta.json b/src/i18n/uk/docs/meta.json index 1cee5e65d..60f557d82 100644 --- a/src/i18n/uk/docs/meta.json +++ b/src/i18n/uk/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "uk" } -} \ No newline at end of file +} diff --git a/src/i18n/uk/docs/module_resolution.md b/src/i18n/uk/docs/module_resolution.md index 3641e176f..5e4a08170 100644 --- a/src/i18n/uk/docs/module_resolution.md +++ b/src/i18n/uk/docs/module_resolution.md @@ -9,7 +9,7 @@ Parcel (v1.7.0 і вище) підтримує декілька стратегі ## Абсолютний шлях -`/foo` буде `foo` по відношенню до **project root**. +`/foo` буде `foo` по відношенню до **project root**. ## ~ Tilde Paths @@ -63,7 +63,7 @@ Parcel (v1.7.0 і вище) підтримує декілька стратегі ```js // electron-ipc.js -module.exports = require("electron").ipcRenderer; +module.exports = require('electron').ipcRenderer ``` ### TypeScript ~ Resolution diff --git a/src/i18n/uk/docs/packagers.md b/src/i18n/uk/docs/packagers.md index 1e42d964b..bd55fb47c 100644 --- a/src/i18n/uk/docs/packagers.md +++ b/src/i18n/uk/docs/packagers.md @@ -1,6 +1,6 @@ # 📦 Пакувальники -У Parcel `Packager` об'єднує кілька` Assets` разом в кінцевий вихідний бандл. Це відбувається в основному процесі після того, як всі ресурси оброблені і створено дерево бандлів. Пакувальники реєструються на основі типу вихідного файлу, а ресурси, які згенерували цей тип виведення, відправляються в бандл для створення остаточного вихідного файлу. +У Parcel `Packager` об'єднує кілька`Assets` разом в кінцевий вихідний бандл. Це відбувається в основному процесі після того, як всі ресурси оброблені і створено дерево бандлів. Пакувальники реєструються на основі типу вихідного файлу, а ресурси, які згенерували цей тип виведення, відправляються в бандл для створення остаточного вихідного файлу. ## Інтерфейс пакувальника @@ -34,4 +34,4 @@ const Bundler = require('parcel-bundler'); let bundler = new Bundler('input.js'); bundler.addPackager('foo', require.resolve('./MyPackager')); -``` \ No newline at end of file +``` diff --git a/src/i18n/uk/docs/plugins.md b/src/i18n/uk/docs/plugins.md index 9c04de15e..e6677c22d 100644 --- a/src/i18n/uk/docs/plugins.md +++ b/src/i18n/uk/docs/plugins.md @@ -19,4 +19,4 @@ module.exports = function(bundler) { ## Використання плагінів -Використання плагінів в Parcel не може бути простіше. Все, що вам потрібно зробити, це встановити і зберегти їх в своєму `package.json`. Модулі повинні мати префікс `parcel-plugin-` (наприклад, `parcel-plugin-foo`). Будь-які залежності, перераховані в `package.json` з цим префіксом, будуть автоматично завантажені при ініціалізації. \ No newline at end of file +Використання плагінів в Parcel не може бути простіше. Все, що вам потрібно зробити, це встановити і зберегти їх в своєму `package.json`. Модулі повинні мати префікс `parcel-plugin-` (наприклад, `parcel-plugin-foo`). Будь-які залежності, перераховані в `package.json` з цим префіксом, будуть автоматично завантажені при ініціалізації. diff --git a/src/i18n/uk/docs/production.md b/src/i18n/uk/docs/production.md index b569972ed..586fc6a04 100644 --- a/src/i18n/uk/docs/production.md +++ b/src/i18n/uk/docs/production.md @@ -7,6 +7,7 @@ parcel build entry.js ``` ## Оптимізації + Це відключає режим перегляду, гарячу заміну модулів, ваш додаток буде зібрано лише один раз і дозволяє мінімізувати всі вихідні бандли для зменшення розміру файлу. Мініфікатори, використовувані Parcel: [terser](https://github.com/fabiosantoscode/terser) для JavaScript, [cssnano](http://cssnano.co) для CSS і [htmlnano](https://github.com/posthtml/htmlnano) для HTML. Включення режиму продакшена також встановлює змінну середовища `NODE_ENV = production`. Великі бібліотеки, такі як React, мають тільки функціональність для налагодження, яка відключається через цю змінну середовища, що призводить до менших і швидших збірок для продакшена. @@ -17,15 +18,15 @@ parcel build entry.js Parcel слідує за наведеною нижче таблицею, коли мова йде про імена бандлів. (Вхідні точки ніколи не хешуються) -| Тип бандлу | Тип | Вміст хешується | -| ---:| --- |:---:|:---:| -| Any | Entrypoint | ❌ | -| JavaScript | ` diff --git a/src/i18n/zh-tw/docs/rust.md b/src/i18n/zh-tw/docs/rust.md index cab596462..aa0d15f9c 100644 --- a/src/i18n/zh-tw/docs/rust.md +++ b/src/i18n/zh-tw/docs/rust.md @@ -1,6 +1,6 @@ # Rust -*支援的副檔名:`rs`* +_支援的副檔名:`rs`_ [Rust](https://www.rust-lang.org/en-US/) 是款由 Mozilla 開發的系統程式語言,其特點有記憶體及執行緒安全性等。Rust 近來支援了 WebAssembly 的編譯,而 Parcel 讓它簡單到**完全無須設定**即可使用! @@ -10,11 +10,11 @@ ```js // 同步地匯入 -import {add} from './add.rs'; -console.log(add(2, 3)); +import { add } from './add.rs' +console.log(add(2, 3)) // 非同步地匯入 -const {add} = await import('./add.rs'); -console.log(add(2, 3)); +const { add } = await import('./add.rs') +console.log(add(2, 3)) ``` 而在 Rust 中,你只需要確保函式為公開函式 (public function) 且無名稱修飾 (name mangling)。 diff --git a/src/i18n/zh-tw/docs/scss.md b/src/i18n/zh-tw/docs/scss.md index c6eb372f9..053f5edc4 100644 --- a/src/i18n/zh-tw/docs/scss.md +++ b/src/i18n/zh-tw/docs/scss.md @@ -1,13 +1,17 @@ # SCSS -*支援的副檔名:`sass` 及 `scss`* +_支援的副檔名:`sass` 及 `scss`_ 編譯 SCSS 需要先使用 npm 安裝 `sass` 模組 (JS 版本的 `dart-sass`): + ```bash npm install sass ``` + 安裝 `sass` 後,你可以從 JavaScript 檔案中匯入 SCSS 檔案。 + ```javascript import './custom.scss' ``` + SCSS 中的相依檔案可透過 `@import` 語法使用。 diff --git a/src/i18n/zh-tw/docs/stylus.md b/src/i18n/zh-tw/docs/stylus.md index b7d0866a1..59fe4af90 100644 --- a/src/i18n/zh-tw/docs/stylus.md +++ b/src/i18n/zh-tw/docs/stylus.md @@ -1,3 +1,3 @@ # Stylus -*支援的副檔名:`stylus`* +_支援的副檔名:`stylus`_ diff --git a/src/i18n/zh-tw/docs/toml.md b/src/i18n/zh-tw/docs/toml.md index 409d35f09..776acb5f7 100644 --- a/src/i18n/zh-tw/docs/toml.md +++ b/src/i18n/zh-tw/docs/toml.md @@ -1,3 +1,3 @@ # TOML -*支援的副檔名:`toml`* +_支援的副檔名:`toml`_ diff --git a/src/i18n/zh-tw/docs/typeScript.md b/src/i18n/zh-tw/docs/typeScript.md index d030bab80..71927aefc 100644 --- a/src/i18n/zh-tw/docs/typeScript.md +++ b/src/i18n/zh-tw/docs/typeScript.md @@ -1,6 +1,6 @@ # TypeScript -*支援的副檔名`ts` 及 `tsx`* +_支援的副檔名`ts` 及 `tsx`_ [TypeScript](https://www.typescriptlang.org/) 是個強型別語法的 JavaScript 超集合,其可支援 ES2015+ 的功能並可編譯成一般的 JavaScript。 @@ -17,11 +17,11 @@ Parcel 已內建 TypeScript 的轉換,完全無需設定。 ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` diff --git a/src/i18n/zh-tw/docs/vue.md b/src/i18n/zh-tw/docs/vue.md index 843aad7be..8dbf39d54 100644 --- a/src/i18n/zh-tw/docs/vue.md +++ b/src/i18n/zh-tw/docs/vue.md @@ -1,3 +1,3 @@ # Vue -*支援的副檔名:`vue`* +_支援的副檔名:`vue`_ diff --git a/src/i18n/zh-tw/docs/webAssembly.md b/src/i18n/zh-tw/docs/webAssembly.md index 0f9b3edcd..6c7e2983c 100644 --- a/src/i18n/zh-tw/docs/webAssembly.md +++ b/src/i18n/zh-tw/docs/webAssembly.md @@ -1,6 +1,6 @@ # WebAssembly -*支援的副檔名:`wasm`* +_支援的副檔名:`wasm`_ [WebAssembly](https://webassembly.org) 是個新興的技術,其對網頁的發展具有相當的影響力,目前各大瀏覽器都已對其提供支援。如同 Node.js 一樣,WebAssembly 將可增加網頁語言的多樣性,且不只限於能轉譯為 JavaScript 的語言。 @@ -10,11 +10,11 @@ C 及 Rust 等等的低階語言都能被編譯為 WebAssembly,而其作為二 ```js // 同步地匯入 -import {add} from './add.wasm'; -console.log(add(2, 3)); +import { add } from './add.wasm' +console.log(add(2, 3)) // 非同步地匯入 -const {add} = await import('./add.wasm'); -console.log(add(2, 3)); +const { add } = await import('./add.wasm') +console.log(add(2, 3)) ``` 當同步地載入 `.wasm` 檔案時,Parcel 會自動產生額外的程式碼以便在執行 JavaScript bundle 之前先行載入檔案,這意味著你的二進制檔不會被當成字串而插入在 JavaScript 中,而是以獨立檔案的形式載入。如此一來你的程式仍可以同步的方式運作,Parcel 則會在前頭替你處理相依套件的載入。 diff --git a/src/i18n/zh-tw/docs/webManifest.md b/src/i18n/zh-tw/docs/webManifest.md index 35153aa88..e32a91257 100644 --- a/src/i18n/zh-tw/docs/webManifest.md +++ b/src/i18n/zh-tw/docs/webManifest.md @@ -1,3 +1,3 @@ # WebManifest -*支援的副檔名:`webmanifest`* +_支援的副檔名:`webmanifest`_ diff --git a/src/i18n/zh-tw/docs/yaml.md b/src/i18n/zh-tw/docs/yaml.md index ce1337b1b..402c0f81c 100644 --- a/src/i18n/zh-tw/docs/yaml.md +++ b/src/i18n/zh-tw/docs/yaml.md @@ -1,3 +1,3 @@ # YAML -*支援的副檔名:`yaml` 及 `yml`* +_支援的副檔名:`yaml` 及 `yml`_ diff --git a/src/i18n/zh/docs/api.md b/src/i18n/zh/docs/api.md index 78c863378..3d22ada63 100644 --- a/src/i18n/zh/docs/api.md +++ b/src/i18n/zh/docs/api.md @@ -4,6 +4,7 @@ 你可以选择使用 API 替代 CLI 来初始化 bundler 对象,以获取更高级的使用方式(例如:在每次构建时进行自定义操作)。 针对每个选项都给出了可参考的示例进行解释说明: + ```Javascript const Bundler = require('parcel-bundler'); const Path = require('path'); @@ -41,7 +42,8 @@ const bundle = await bundler.bundle(); 这是所有的 bundler 事件列表。 -* 一旦 parcel 完成打包,会调用 `bundled`,主 [bundle](#bundle) 会作为参数传递到该 callback +- 一旦 parcel 完成打包,会调用 `bundled`,主 [bundle](#bundle) 会作为参数传递到该 callback + ```Javascript const bundler = new Bundler(...); bundler.on('bundled', (bundler) => { @@ -49,7 +51,8 @@ bundler.on('bundled', (bundler) => { }); ``` -* 每次构建结束后,都会调用 `buildEnd`,即使发生错误它也仍然会被触发 +- 每次构建结束后,都会调用 `buildEnd`,即使发生错误它也仍然会被触发 + ```Javascript const bundler = new Bundler(...); bundler.on('buildEnd', () => { @@ -63,21 +66,20 @@ bundler.on('buildEnd', () => { #### 属性 -* `type`:它包含的资源类型 (例如:js, css, map, ...) -* `name`:bundle 的名称 (使用 `entryAsset` 的 `Asset.generateBundleName()` 生成) -* `parentBundle`:父 bundle ,入口 bundle 的父 bundle 是 null -* `entryAsset`:bundle 的入口,用于生成名称(name)和聚拢资源(assets) -* `assets`:bundle 中所有资源的`集合(Set)` -* `childBundles`:所有子 bundle 的`集合(Set)` -* `siblingBundles`:所有兄弟 bundle 的`集合(Set)` -* `siblingBundlesMap`:所有兄弟 bundle 的映射 `Map` -* `offsets`:所有 bundle 中资源位置的映射 `Map` ,用于生成准确的 sourcemap 。 +- `type`:它包含的资源类型 (例如:js, css, map, ...) +- `name`:bundle 的名称 (使用 `entryAsset` 的 `Asset.generateBundleName()` 生成) +- `parentBundle`:父 bundle ,入口 bundle 的父 bundle 是 null +- `entryAsset`:bundle 的入口,用于生成名称(name)和聚拢资源(assets) +- `assets`:bundle 中所有资源的`集合(Set)` +- `childBundles`:所有子 bundle 的`集合(Set)` +- `siblingBundles`:所有兄弟 bundle 的`集合(Set)` +- `siblingBundlesMap`:所有兄弟 bundle 的映射 `Map` +- `offsets`:所有 bundle 中资源位置的映射 `Map` ,用于生成准确的 sourcemap 。 #### 树 `Bundle` 包含一个 `parentBundle`,`childBundles` 和 `siblingBundles`,所有这些属性一起创建一个快速迭代的 bundle 树。 - 资源树及其生成的 bundle 树的基本示例如下: ##### 资源树: @@ -120,6 +122,7 @@ index.html 中间件可以用于 hook 到 http 服务器(例如:`express` 或者 Node.js `http`) 。 使用 express 的 parcel 中间件示例: + ```Javascript const Bundler = require('parcel-bundler'); const app = require('express')(); diff --git a/src/i18n/zh/docs/asset_types.md b/src/i18n/zh/docs/asset_types.md index 3c6d87264..ae8f143e3 100755 --- a/src/i18n/zh/docs/asset_types.md +++ b/src/i18n/zh/docs/asset_types.md @@ -2,19 +2,19 @@ 正如 [资源文档](assets.html) 里描述的,Parcel 将输入的文件看作 `资源(Asset)`。资源类型被看作继承自基准 `Asset`类的子类,并实现了必须的接口,去解析、分析依赖、转换及生成代码。 -因为 Parcel 在多处理器内核中并行处理资源,因此资源类型所能够实施的转换行为,会被限制为那些可以在单一时间内操作单一文件的转换行为。而那些需要操作多个文件的转换行为,则需要一个自定义的[Packager](packagers.html)。 +因为 Parcel 在多处理器内核中并行处理资源,因此资源类型所能够实施的转换行为,会被限制为那些可以  在单一时间内操作单一文件的转换行为。而那些需要操作多个文件的转换行为,则需要一个自定义的[Packager](packagers.html)。 ## 资源接口 ```javascript -const {Asset} = require('parcel-bundler'); +const { Asset } = require('parcel-bundler') class MyAsset extends Asset { - type = 'foo'; // 设置主要输出类型 + type = 'foo' // 设置主要输出类型 async parse(code) { // 将代码解析为 AST 树 - return ast; + return ast } async pretransform() { @@ -23,7 +23,7 @@ class MyAsset extends Asset { collectDependencies() { // 分析依赖 - this.addDependency('my-dep'); + this.addDependency('my-dep') } async transform() { @@ -43,7 +43,7 @@ class MyAsset extends Asset { value: 'some javascript', // 如若需要,此转换内容可被放到 JS 的 bundle 中 sourceMap } - ]; + ] } async postProcess(generated) { @@ -58,8 +58,8 @@ class MyAsset extends Asset { 你可以用 `addAssetType` 方法在打包工具中去注册你的资源类型。它接受一个文件扩展名,以及资源类型模块的路径。它是一个路径,而非实际的对象,这样可以使它被传至 worker 进程中。 ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addAssetType('.ext', require.resolve('./MyAsset')); +let bundler = new Bundler('input.js') +bundler.addAssetType('.ext', require.resolve('./MyAsset')) ``` diff --git a/src/i18n/zh/docs/assets.md b/src/i18n/zh/docs/assets.md index 6675946ec..6fa2b1542 100644 --- a/src/i18n/zh/docs/assets.md +++ b/src/i18n/zh/docs/assets.md @@ -1,6 +1,6 @@ # 📦 资源(Assets) -Parcel 是基于资源的,资源可以代表任意文件,并且 Parcel 对 JavaScript,CSS,HTML 文件有更多的支持。 Parcel 会自动地分析这些文件和包中引用的依赖。相同类型的资源会被组合到同一捆绑包中。如果导入其他类型的资源(例如:你在 JS 文件中导入 CSS 文件),Parcel会启动子捆绑包,并在父捆绑包中保留对它的引用。这一点将在以下部分进行说明。 +Parcel 是基于资源的,资源可以代表任意文件,并且 Parcel 对 JavaScript,CSS,HTML 文件有更多的支持。 Parcel 会自动地分析这些文件和包中引用的依赖。相同类型的资源会被组合到同一捆绑包中。如果导入其他类型的资源(例如:你在 JS 文件中导入 CSS 文件),Parcel 会启动子捆绑包,并在父捆绑包中保留对它的引用。这一点将在以下部分进行说明。 ## JavaScript @@ -8,40 +8,40 @@ JavaScript 是最传统的 Web 打包文件类型。 Parcel 同时支持 CommonJ ```javascript // 使用 CommonJS 语法导入模块 -const dep = require('./path/to/dep'); +const dep = require('./path/to/dep') // 使用 ES6 语法导入模块 -import dep from './path/to/dep'; +import dep from './path/to/dep' ``` -你也能在 JavaScript 文件中导入非 JavaScript 资源,例如:CSS 文件及图片文件。导入这类文件时,Parcel不会像其他打包工具一样内联该文件,而是将所有的依赖放置在另外一个捆绑包里(例如:一个 CSS 文件)。当使用 [CSS Modules](https://github.com/css-modules/css-modules) 时,这个导出类会被放置在 JavaScript 包里。其他的资源文件将以 URL 的形式导出到 JavaScript 包中的 output 中,以便于能在你的代码中引用。 +你也能在 JavaScript 文件中导入非 JavaScript 资源,例如:CSS 文件及图片文件。导入这类文件时,Parcel 不会像其他打包工具一样内联该文件,而是将所有的依赖放置在另外一个捆绑包里(例如:一个 CSS 文件)。当使用 [CSS Modules](https://github.com/css-modules/css-modules) 时,这个导出类会被放置在 JavaScript 包里。其他的资源文件将以 URL 的形式导出到 JavaScript 包中的 output 中,以便于能在你的代码中引用。 ```javascript // 引入 CSS 文件 -import './test.css'; +import './test.css' // 引入包含 CSS 模块的 CSS 文件 -import classNames from './test.css'; +import classNames from './test.css' // 以 URL 的形式引入图片 -import imageURL from './test.png'; +import imageURL from './test.png' ``` 如果你想通过内联文件到 JavaScript 包取代 URL 引入文件的方式,你可以使用 Node.js 的 `fs.readFileSync` API。URL 必须是静态可分析的,意味着它不能有任何变量(除了`__dirname` 和 `__filename`)。 ```javascript -import fs from 'fs'; +import fs from 'fs' // 以字符串的形式读取内容 -const string = fs.readFileSync(__dirname + '/test.txt', 'utf8'); +const string = fs.readFileSync(__dirname + '/test.txt', 'utf8') // 以 Buffer 的形式读取内容 -const buffer = fs.readFileSync(__dirname + '/test.png'); +const buffer = fs.readFileSync(__dirname + '/test.png') ``` ## CSS -JavaScript 文件或 HTML 文件都能导入 CSS 资源,并且能通过 `@import` 语法引用依赖,还能通过 `url()` 函数引入图片,字体等。其他通过 `@import` 导入的 CSS 文件被内联到同一个CSS包里,并将 `url()` 引用重写为其输出文件名。所有文件名都应该与当前 CSS 文件相关联。 +JavaScript 文件或 HTML 文件都能导入 CSS 资源,并且能通过 `@import` 语法引用依赖,还能通过 `url()` 函数引入图片,字体等。其他通过 `@import` 导入的 CSS 文件被内联到同一个 CSS 包里,并将 `url()` 引用重写为其输出文件名。所有文件名都应该与当前 CSS 文件相关联。 ```css /* 引入其他 CSS 文件 */ @@ -53,17 +53,22 @@ JavaScript 文件或 HTML 文件都能导入 CSS 资源,并且能通过 `@impo } ``` -除了普通的 CSS,其他的 LESS,SASS,以及 Stylus 等CSS预处理器语言也是支持的,并且执行方法是与之相同的。 +除了普通的 CSS,其他的 LESS,SASS,以及 Stylus 等 CSS 预处理器语言也是支持的,并且执行方法是与之相同的。 ## SCSS + 编译 SCSS 需要 `sass` 模块. 通过 npm 安装它: + ```bash npm install sass ``` + 一旦安装了 `sass`,你就可以在 JavaScript 文件中引入 SCSS 文件。 + ```javascript import './custom.scss' ``` + SCSS 文件中的依赖可以使用 `@import` 语句。 ## HTML diff --git a/src/i18n/zh/docs/cli.md b/src/i18n/zh/docs/cli.md index c7eaac316..bab52a27f 100644 --- a/src/i18n/zh/docs/cli.md +++ b/src/i18n/zh/docs/cli.md @@ -95,12 +95,12 @@ parcel build entry.js --target node parcel entry.js --log-level 1 ``` -| 日志等级 | 效果 | -|--- |--- | -| 0 | 禁用记录 | -| 1 | 只记录错误 | -| 2 | 记录错误和警告 | -| 3 | 记录一切 | +| 日志等级 | 效果 | +| -------- | -------------- | +| 0 | 禁用记录 | +| 1 | 只记录错误 | +| 2 | 记录错误和警告 | +| 3 | 记录一切 | ### HMR 主机名 @@ -224,4 +224,4 @@ parcel build entry.js --no-minify ```bash parcel build entry.js --no-cache -``` \ No newline at end of file +``` diff --git a/src/i18n/zh/docs/code_splitting.md b/src/i18n/zh/docs/code_splitting.md index 7a872bedb..9849574ff 100755 --- a/src/i18n/zh/docs/code_splitting.md +++ b/src/i18n/zh/docs/code_splitting.md @@ -12,19 +12,20 @@ export function render() { // 渲染页面 } ``` + ```javascript -import('./pages/about').then(function (page) { +import('./pages/about').then(function(page) { // 渲染页面 - page.render(); -}); + page.render() +}) ``` -因为 `import()` 返回一个Promise,所以你也可以使用 async/await 语法。不过,在浏览器广泛支持它之前,你可能需要配置 Babel 来转换语法。 +因为 `import()` 返回一个 Promise,所以你也可以使用 async/await 语法。不过,在浏览器广泛支持它之前,你可能需要配置 Babel 来转换语法。 ```javascript -const page = await import('./pages/about'); +const page = await import('./pages/about') // 渲染页面 -page.render(); +page.render() ``` 动态导入也会在 Parcel 中延迟加载,因此你仍然需要将所有的 `import()` 调用放在文件的顶部,并且在使用子捆绑包之前,它们不会被加载。以下示例展示如何动态地延迟加载应用程序的子页面。 @@ -35,12 +36,12 @@ page.render(); const pages = { about: import('./pages/about'), blog: import('./pages/blog') -}; +} async function renderPage(page) { // 懒加载请求页面。 - const page = await pages[page]; - return page.render(); + const page = await pages[page] + return page.render() } ``` @@ -51,8 +52,8 @@ yarn add babel-polyfill ``` ```javascript -import "babel-polyfill"; -import "./app"; +import 'babel-polyfill' +import './app' ``` 请参阅 [babel-polyfill](http://babeljs.cn/docs/usage/polyfill) 和 [babel-runtime](http://babeljs.cn/docs/plugins/transform-runtime) 的文档。 diff --git a/src/i18n/zh/docs/getting_started.md b/src/i18n/zh/docs/getting_started.md index 2b4ed3b7e..97b3a5f81 100644 --- a/src/i18n/zh/docs/getting_started.md +++ b/src/i18n/zh/docs/getting_started.md @@ -5,11 +5,13 @@ Parcel 是 Web 应用打包工具,适用于经验不同的开发者。它利 首先通过 Yarn 或者 npm 安装 Parcel : Yarn: + ```bash yarn global add parcel-bundler ``` npm: + ```bash npm install -g parcel-bundler ``` @@ -19,7 +21,9 @@ npm install -g parcel-bundler ```bash yarn init -y ``` -or + +or + ```bash npm init -y ``` @@ -37,7 +41,7 @@ Parcel 可以使用任何类型的文件作为入口,但是最好还是使用 ``` ```javascript -console.log("hello world"); +console.log('hello world') ``` Parcel 内置了一个当你改变文件时能够自动重新构建应用的开发服务器,而且为了实现快速开发,该开发服务器支持[热模块替换](hmr.html)。只需要在入口文件指出: @@ -54,4 +58,3 @@ parcel watch index.html ``` 当你准备在生产模式下创建,`build` 模式会关闭监听并且只建立一次。请查阅 [Production](production.html) 查看更多细节。 - diff --git a/src/i18n/zh/docs/hmr.md b/src/i18n/zh/docs/hmr.md index 5ee7f07d9..e400ac797 100755 --- a/src/i18n/zh/docs/hmr.md +++ b/src/i18n/zh/docs/hmr.md @@ -8,22 +8,23 @@ ```javascript if (module.hot) { - module.hot.dispose(function () { + module.hot.dispose(function() { // 模块即将被替换时 - }); + }) - module.hot.accept(function () { + module.hot.accept(function() { // 模块或其依赖项之一刚刚更新时 - }); + }) } ``` ## 安全写入(Safe Write) + 一些文本编辑器和 IDE 均有`安全写入`的功能,这基本上可以防止数据丢失,通过获取文本的副本并在保存时对其进行重命名操作。 当使用热模块重载 (HMR) 时,此功能会阻止文件更新的自动检测,要禁用`安全写入`,请使用下列提供的选项: -* `Sublime Text 3` 将 atomic_save: "false" 添加到你用户设置中。 -* `IntelliJ` 在设置中使用搜索来查找 "safe write" 并将其禁用。 -* `Vim` 添加 :set backupcopy=yes 到你的设置中. -* `WebStorm` 在 Preferences > Appearance & Behavior > System Settings 中取消选中 "safe write" 选项。 +- `Sublime Text 3` 将 atomic_save: "false" 添加到你用户设置中。 +- `IntelliJ` 在设置中使用搜索来查找 "safe write" 并将其禁用。 +- `Vim` 添加 :set backupcopy=yes 到你的设置中. +- `WebStorm` 在 Preferences > Appearance & Behavior > System Settings 中取消选中 "safe write" 选项。 diff --git a/src/i18n/zh/docs/meta.json b/src/i18n/zh/docs/meta.json index 376cc46eb..9a53fbba4 100644 --- a/src/i18n/zh/docs/meta.json +++ b/src/i18n/zh/docs/meta.json @@ -2,4 +2,4 @@ "*": { "language": "zh" } -} \ No newline at end of file +} diff --git a/src/i18n/zh/docs/packagers.md b/src/i18n/zh/docs/packagers.md index 5922b1332..bede8b9a8 100755 --- a/src/i18n/zh/docs/packagers.md +++ b/src/i18n/zh/docs/packagers.md @@ -5,22 +5,22 @@ ## Packager 接口 ```javascript -const {Packager} = require('parcel-bundler'); +const { Packager } = require('parcel-bundler') class MyPackager extends Packager { async start() { // 可选,写文件头部内容 - await this.dest.write(header); + await this.dest.write(header) } async addAsset(asset) { // 必须。将资源写入生成文件。 - await this.dest.write(asset.generated.foo); + await this.dest.write(asset.generated.foo) } async end() { // 可选,写文件尾内部内容。 - await this.dest.end(trailer); + await this.dest.end(trailer) } } ``` @@ -30,8 +30,8 @@ class MyPackager extends Packager { 你可以用 `addPackager` 方法在打包工具中注册一个 packager。它接受一个文件类型及 packager 模块的所在路径用于注册。 ```javascript -const Bundler = require('parcel-bundler'); +const Bundler = require('parcel-bundler') -let bundler = new Bundler('input.js'); -bundler.addPackager('foo', require.resolve('./MyPackager')); +let bundler = new Bundler('input.js') +bundler.addPackager('foo', require.resolve('./MyPackager')) ``` diff --git a/src/i18n/zh/docs/plugins.md b/src/i18n/zh/docs/plugins.md index 3e48dd71f..049fd6655 100755 --- a/src/i18n/zh/docs/plugins.md +++ b/src/i18n/zh/docs/plugins.md @@ -4,17 +4,15 @@ Parcel 采用与许多其它工具稍微不同的策略,许多常见的格式 当你添加一种全新的文件格式到 Parcel,你应该先考虑它会有多通用,还有它的实现会有多标准化。如果它足够通用及标准,该格式很可能应该被添加到 Parcel 的核心,而不是作为一种用户需要安装的插件。如果你有其它的疑惑,可以到[GitHub](https://github.com/parcel-bundler/parcel/issues)一起讨论。 - ## 插件 API Parcel 插件很简单。它们只是简单地将几个模块输出成一个函数,它会被 Parcel 在初始化的时候自动调用。函数接收 `Bundler` 对象作为输入,也可以做一些配置,比如注册资源类型和注册 packager。 - ```javascript -module.exports = function (bundler) { - bundler.addAssetType('ext', require.resolve('./MyAsset')); - bundler.addPackager('foo', require.resolve('./MyPackager')); -}; +module.exports = function(bundler) { + bundler.addAssetType('ext', require.resolve('./MyAsset')) + bundler.addPackager('foo', require.resolve('./MyPackager')) +} ``` 请发布这个包到 npm,并使用 `parcel-plugin-` 前缀,那它就会像后文提到的那样被自动检测和加载。 diff --git a/src/i18n/zh/docs/transforms.md b/src/i18n/zh/docs/transforms.md index f601eb3a9..8f79df177 100755 --- a/src/i18n/zh/docs/transforms.md +++ b/src/i18n/zh/docs/transforms.md @@ -68,9 +68,9 @@ Parcel 在生产环境构建时,会使用 [cssnano](http://cssnano.co) 来压 module.exports = { calc: false, discardComments: { - removeAll: true, + removeAll: true } -}; +} ``` ## PostHTML @@ -112,13 +112,13 @@ Plugins 在 `plugins` 对象中指定为 key,并且选项使用对象值定义 ```typescript // index.ts -import message from "./message"; -console.log(message); +import message from './message' +console.log(message) ``` ```typescript // message.ts -export default "Hello, world"; +export default 'Hello, world' ``` ## ReasonML/BuckleScript @@ -144,8 +144,7 @@ $ yarn add bs-platform --dev "in-source": true }, "suffix": ".bs.js", - "bs-dependencies": [ - ], + "bs-dependencies": [], "warnings": { "error": "+101" }, diff --git a/src/server.js b/src/server.js index 4707f95d1..460a44acf 100644 --- a/src/server.js +++ b/src/server.js @@ -1,28 +1,30 @@ -const express = require('express'); -const fs = require('fs'); +const express = require('express') +const fs = require('fs') -const app = express(); -const languages = fs.readdirSync(__dirname + '/../dist'); +const app = express() +const languages = fs.readdirSync(__dirname + '/../dist') if (languages.length === 0) { - console.log("Please run 'npm run build' first."); - process.exit(); + console.log("Please run 'npm run build' first.") + process.exit() } -app.use(function (req, res, next) { +app.use(function(req, res, next) { // autodetect language let lang = [req.query.locale, req.subdomains[0], req.acceptsLanguages(...languages), 'en'].find(function(lang) { - return languages.includes(lang); - }); + return languages.includes(lang) + }) - req.url = '/' + lang + req.url; - res.setHeader('Content-Language', lang); - next(); -}); + req.url = '/' + lang + req.url + res.setHeader('Content-Language', lang) + next() +}) -app.use(express.static(__dirname + '/../dist', { - maxAge: 60000 -})); +app.use( + express.static(__dirname + '/../dist', { + maxAge: 60000 + }) +) -app.listen(5000); -console.log('Listening on port 5000'); +app.listen(5000) +console.log('Listening on port 5000')