diff --git a/src/content/api/loaders.md b/src/content/api/loaders.md index 6e2d749c9ef0..f22f2584703f 100755 --- a/src/content/api/loaders.md +++ b/src/content/api/loaders.md @@ -261,7 +261,7 @@ T> loader 最初被设计为可以同时当 Babel transform 用。如果你编 ### `this.emitWarning` ```typescript -emitWarning(message: string) +emitWarning(warning: Error) ``` 发出一个警告。 @@ -270,7 +270,7 @@ emitWarning(message: string) ### `this.emitError` ```typescript -emitError(message: string) +emitError(error: Error) ``` 发出一个错误。 diff --git a/src/content/concepts/index.md b/src/content/concepts/index.md index f727326f6cbc..e748a05d291f 100755 --- a/src/content/concepts/index.md +++ b/src/content/concepts/index.md @@ -1,5 +1,5 @@ --- -title: 核心概念 +title: 概念 sort: 1 contributors: - TheLarkInn @@ -7,41 +7,47 @@ contributors: - grgur - johnstew - jimrfenner + - TheDutchCoder --- -*webpack* 是一个现代 JavaScript 应用程序的_模块打包器(module bundler)_。当 webpack 处理应用程序时,它会递归地构建一个_依赖关系图(dependency graph)_,其中包含应用程序需要的每个模块,然后将所有这些模块打包成少量的 _bundle_ - 通常只有一个,由浏览器加载。 +本质上,*webpack* 是一个现代 JavaScript 应用程序的_模块打包器(module bundler)_。当 webpack 处理应用程序时,它会递归地构建一个_依赖关系图(dependency graph)_,其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 _bundle_。 -它是[高度可配置的](/configuration),但是,在开始前你需要先理解**四个核心概念**:入口(entry)、输出(output)、loader、插件(plugins)。 +它是[高度可配置的](/configuration),但是,在开始前你需要先理解四个**核心概念**: + +- 入口(entry) +- 输出(output) +- loader +- 插件(plugins) 本文档旨在给出这些概念的**高度**概述,同时提供具体概念的详尽相关用例。 -## 入口(Entry) +## 入口(entry) -webpack 创建应用程序所有依赖的关系图(dependency graph)。图的起点被称之为_入口起点(entry point)_。_入口起点_告诉 webpack _从哪里开始_,并根据依赖关系图确定_需要打包的内容_。可以将应用程序的_入口起点_认为是**根上下文(contextual root)** 或 **app 第一个启动文件**。 +**入口起点(entry point)**指示 webpack 应该使用哪个模块,来作为构建其内部*依赖图*的开始。进入入口起点后,webpack 会找出有哪些模块和库是入口起点(直接和间接)依赖的。 -在 webpack 中,我们使用 [webpack 配置对象(webpack configuration object)](/configuration) 中的 `entry` 属性来定义_入口_。 +每个依赖项随即被处理,最后输出到称之为 *bundles* 的文件中,我们将在下一章节详细讨论这个过程。 -接下来我们看一个最简单的例子: +可以通过在 [webpack 配置](/configuration)中配置 `entry` 属性,来指定一个入口起点(或多个入口起点)。 -**webpack.config.js** +接下来我们看一个 `entry` 配置的最简单例子: -```javascript +__webpack.config.js__ + +``` js module.exports = { entry: './path/to/my/entry/file.js' }; ``` -根据不同应用程序的需要,声明 `entry` 属性有多种方式。 +T> 根据应用程序的特定需求,可以以多种方式配置 `entry` 属性。从[入口起点](/concepts/entry-points)章节可以了解更多信息。 -[了解更多!](/concepts/entry-points) +## 出口(output) -## 出口(Output) +**output** 属性告诉 webpack 在哪里输出它所创建的 *bundles*,以及如何命名这些文件。你可以通过在配置中指定一个 `output` 字段,来配置这些处理过程: -将所有的资源(assets)归拢在一起后,还需要告诉 webpack **在哪里**打包应用程序。webpack 的 `output` 属性描述了**如何处理归拢在一起的代码**(bundled code)。 - -**webpack.config.js** +__webpack.config.js__ ```javascript const path = require('path'); @@ -59,20 +65,18 @@ module.exports = { T> 你可能看到项目**生成(emitted 或 emit)**贯穿我们整个文档和[插件 API](/api/plugins)。它是“生产(produced)”或“排放(discharged)”的特殊术语。 - `output` 属性还有[更多可配置的特性](/configuration/output),但让我们花一些时间先了解一些 `output` 属性最常见的用例。 - -[了解更多!](/concepts/output) +T> `output` 属性还有[更多可配置的特性](/configuration/output),如果你想要了解更多关于 `output` 属性的概念,你可以通过[阅读核心章节]more in the concepts section](/concepts/output)来了解更多。 -## Loader +## loader -webpack 的目标是,让 **webpack** 聚焦于项目中的所有资源(asset),而浏览器不需要关注考虑这些(明确的说,这并不意味着所有资源(asset)都必须打包在一起)。webpack 把[每个文件(.css, .html, .scss, .jpg, etc.) 都作为模块](/concepts/modules)处理。然而 webpack 自身**只理解 JavaScript**。 +*loader* 能够让 webpack 额外去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。loader 可以将所有类型的文件转换为有效的[模块](/concepts/modules),然后再利用 webpack 的打包能力,对它们进行处理。 -**webpack loader 在文件被添加到依赖图中时,_其转换为模块_。** +本质上,webpack loader 将所有类型的文件,转换为应用程序的依赖图可以直接引用的模块。 在更高层面,在 webpack 的配置中 **loader** 有两个目标。 -1. 识别出(identify)应该被对应的 loader 进行转换(transform)的那些文件。(`test` 属性) +1. 识别出应该被对应的 loader 进行转换的那些文件。(使用 `test` 属性) 2. 转换这些文件,从而使其能够被添加到依赖图中(并且最终添加到 bundle 中)(`use` 属性) **webpack.config.js** @@ -107,17 +111,17 @@ loader 还有更多我们尚未提到的具体配置属性。 [了解更多!](/concepts/loaders) -## 插件(Plugins) +## 插件(plugins) -然而由于 loader 仅在每个文件的基础上执行转换,而 `插件(plugins)` 更常用于(但不限于)在打包模块的 “compilation” 和 “chunk” 生命周期执行操作和自定义功能[(查看更多)](/concepts/plugins)。webpack 的插件系统[极其强大和可定制化](/api/plugins)。 +loader 被用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量。[插件接口](/api/plugins)功能极其强大,可以用来处理各种各样的任务。 -想要使用一个插件,你只需要 `require()` 它,然后把它添加到 `plugins` 数组中。多数插件可以通过选项(option)自定义。你也可以在一个配置文件中因为不同目的而多次使用同一个插件,这时需要通过使用 `new` 来创建它的一个实例。 +想要使用一个插件,你只需要 `require()` 它,然后把它添加到 `plugins` 数组中。多数插件可以通过选项(option)自定义。你也可以在一个配置文件中因为不同目的而多次使用同一个插件,这时需要通过使用 `new` 操作符来创建它的一个实例。 **webpack.config.js** ```javascript -const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm -const webpack = require('webpack'); //to access built-in plugins +const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装 +const webpack = require('webpack'); // 用于访问内置插件 const path = require('path'); const config = { diff --git a/src/content/guides/hot-module-replacement.md b/src/content/guides/hot-module-replacement.md index f8d8e8249979..1262cb78e279 100755 --- a/src/content/guides/hot-module-replacement.md +++ b/src/content/guides/hot-module-replacement.md @@ -162,6 +162,8 @@ server.listen(5000, 'localhost', () => { }); ``` +T> If you're [using `webpack-dev-middleware`](/guides/development#using-webpack-dev-middleware), check out the [`webpack-hot-middleware`](https://github.com/glenjamin/webpack-hot-middleware) package to enable HMR on your custom dev server. + ## 问题 diff --git a/src/content/guides/shimming.md b/src/content/guides/shimming.md index 46e68d54c63d..903b2a1c004e 100755 --- a/src/content/guides/shimming.md +++ b/src/content/guides/shimming.md @@ -6,6 +6,7 @@ contributors: - jhnns - simon04 - jeremenichelli + - svyandun related: - title: Reward modern browser users script url: https://hackernoon.com/10-things-i-learned-making-the-fastest-site-in-the-world-18a0e1cdf4a7#c665 @@ -65,6 +66,7 @@ __webpack.config.js__ ``` diff const path = require('path'); ++ const webpack = require('webpack'); module.exports = { entry: './src/index.js', @@ -75,7 +77,7 @@ __webpack.config.js__ + }, + plugins: [ + new webpack.ProvidePlugin({ -+ lodash: 'lodash' ++ _: 'lodash' + }) + ] }; @@ -112,6 +114,7 @@ __webpack.config.js__ ``` diff const path = require('path'); + const webpack = require('webpack'); module.exports = { entry: './src/index.js', @@ -121,7 +124,7 @@ __webpack.config.js__ }, plugins: [ new webpack.ProvidePlugin({ -- lodash: 'lodash' +- _: 'lodash' + join: ['lodash', 'join'] }) ] @@ -156,6 +159,7 @@ __webpack.config.js__ ``` diff const path = require('path'); + const webpack = require('webpack'); module.exports = { entry: './src/index.js', @@ -213,6 +217,7 @@ __webpack.config.js__ ``` diff const path = require('path'); + const webpack = require('webpack'); module.exports = { entry: './src/index.js', @@ -323,6 +328,7 @@ __webpack.config.js__ ``` diff const path = require('path'); + const webpack = require('webpack'); module.exports = { - entry: './src/index.js', diff --git a/src/content/guides/typescript.md b/src/content/guides/typescript.md index 423d9ebcc8d6..330d5d13efad 100755 --- a/src/content/guides/typescript.md +++ b/src/content/guides/typescript.md @@ -78,7 +78,7 @@ module.exports = { ] }, resolve: { - extensions: [ ".tsx", ".ts", ".js" ] + extensions: [ '.tsx', '.ts', '.js' ] }, output: { filename: 'bundle.js', @@ -139,7 +139,7 @@ __webpack.config.js__ ] }, resolve: { - extensions: [ ".tsx", ".ts", ".js" ] + extensions: [ '.tsx', '.ts', '.js' ] }, output: { filename: 'bundle.js', diff --git a/src/content/loaders/babel-loader.md b/src/content/loaders/babel-loader.md index 3d9cce904101..e3f37c0a0b69 100644 --- a/src/content/loaders/babel-loader.md +++ b/src/content/loaders/babel-loader.md @@ -12,20 +12,16 @@ __Notes:__ Issues with the output should be reported on the babel [issue tracker ## 安装 -> webpack 1.x | babel-loader <= 6.x -> -> webpack 2.x | babel-loader >= 7.x (推荐)(^6.2.10 也可以运行,但会有不赞成的警告(deprecation warnings)) -> -> webpack 3.x | babel-loader >= 7.1 +> webpack 3.x | babel-loader 8.x | babel 7.x ```bash -yarn add babel-loader babel-core babel-preset-env webpack --dev +npm install babel-loader@8.0.0-beta.0 @babel/core@next @babel/preset-env@next webpack ``` -我们推荐您使用 yarn,但还是可以使用 npm: +> webpack 3.x babel-loader 7.x | babel 6.x ```bash -npm install --save-dev babel-loader babel-core babel-preset-env webpack +npm install babel-loader babel-core babel-preset-env webpack ``` ## 用法 @@ -43,7 +39,7 @@ module: { use: { loader: 'babel-loader', options: { - presets: ['env'] + presets: ['@babel/preset-env'] } } } @@ -67,8 +63,8 @@ module: { use: { loader: 'babel-loader', options: { - presets: ['env'], - plugins: [require('babel-plugin-transform-object-rest-spread')] + presets: ['@babel/preset-env'], + plugins: [require('@babel/plugin-transform-object-rest-spread')] } } } @@ -119,8 +115,8 @@ rules: [ use: { loader: 'babel-loader', options: { - presets: ['env'], - plugins: ['transform-runtime'] + presets: ['@babel/preset-env'], + plugins: ['@babel/transform-runtime'] } } } @@ -142,7 +138,7 @@ rules: [ 下面这样的写法也没有作用: ```javascript -require('babel-runtime/core-js/promise').default = require('bluebird'); +require('@babel/runtime/core-js/promise').default = require('bluebird'); var promise = new Promise; ``` @@ -152,9 +148,9 @@ var promise = new Promise; ```javascript 'use strict'; -var _Promise = require('babel-runtime/core-js/promise')['default']; +var _Promise = require('@babel/runtime/core-js/promise')['default']; -require('babel-runtime/core-js/promise')['default'] = require('bluebird'); +require('@babel/runtime/core-js/promise')['default'] = require('bluebird'); var promise = new _Promise(); ``` @@ -166,7 +162,7 @@ var promise = new _Promise(); ```javascript // bootstrap.js -require('babel-runtime/core-js/promise').default = require('bluebird'); +require('@babel/runtime/core-js/promise').default = require('bluebird'); // ... diff --git a/src/content/loaders/bundle-loader.md b/src/content/loaders/bundle-loader.md index 1b3b2374120a..882f884a5c26 100644 --- a/src/content/loaders/bundle-loader.md +++ b/src/content/loaders/bundle-loader.md @@ -126,7 +126,7 @@ module.exports = { { test: /\.bundle\.js$/, use: { - loader: 'bundle-loader' + loader: 'bundle-loader', options: { name: 'my-chunk' } diff --git a/src/content/loaders/i18n-loader.md b/src/content/loaders/i18n-loader.md index 8f575e9483a2..d0e975c5816f 100644 --- a/src/content/loaders/i18n-loader.md +++ b/src/content/loaders/i18n-loader.md @@ -43,7 +43,8 @@ locale(function() { ### 配置 -如果想要一次加载然后可以同步地使用,你应该告诉 loader 所有要使用的地区。 +如果想要一次加载然后可以同步地使用, +你应该告诉 loader 所有要使用的地区。 ``` javascript { diff --git a/src/content/loaders/postcss-loader.md b/src/content/loaders/postcss-loader.md index a757b7e95f87..732be744e619 100644 --- a/src/content/loaders/postcss-loader.md +++ b/src/content/loaders/postcss-loader.md @@ -336,7 +336,7 @@ either add the css-loader’s [`importLoaders`] option. or use [postcss-modules] instead of `css-loader`. -[`importLoaders`]: https://github.com/webpack-contrib/css-loader#importing-and-chained-loaders +[`importLoaders`]: https://github.com/webpack-contrib/css-loader#importloaders [cannot be used]: https://github.com/webpack/css-loader/issues/137 [CSS Modules]: https://github.com/webpack/css-loader#css-modules [postcss-modules]: https://github.com/outpunk/postcss-modules diff --git a/src/content/loaders/worker-loader.md b/src/content/loaders/worker-loader.md index e2c90ee645d4..0f7e35ef1893 100644 --- a/src/content/loaders/worker-loader.md +++ b/src/content/loaders/worker-loader.md @@ -1,248 +1,297 @@ ---- -title: worker-loader -source: https://raw.githubusercontent.com/webpack-contrib/worker-loader/master/README.md -edit: https://github.com/webpack-contrib/worker-loader/edit/master/README.md -repo: https://github.com/webpack-contrib/worker-loader ---- -This loader registers the script as Web Worker - - -## 安装 - -```bash -npm i -D worker-loader -``` - -## 用法 - -## - -**App.js** -```js -import Worker from 'worker-loader!./Worker.js' -``` - -### `Config` - -**webpack.config.js** -```js -{ - module: { - rules: [ - { - test: /\.worker\.js$/, - use: { loader: 'worker-loader' } - } - ] - } -} -``` - -**App.js** -```js -import Worker from './file.worker.js' - -const worker = new Worker() - -worker.postMessage({ a: 1 }) -worker.onmessage = function (event) {} - -worker.addEventListener("message", function (event) {}) -``` - -## Options - -|Name|Type|Default|Description| -|:--:|:--:|:-----:|:----------| -|**`name`**|`{String}`|`[hash].worker.js`|Set a custom name for the output script| -|**`inline`**|`{Boolean}`|`false`|Inline the worker as a BLOB| -|**`fallback`**|`{Boolean}`|`false`|Require a fallback for non-worker supporting environments| - -### `name` - -To set a custom name for the output script, use the `name` parameter. The name may contain the string `[hash]`, which will be replaced with a content dependent hash for caching purposes - -*webpack.config.js** -```js -{ - loader: 'worker-loader', - options: { name: 'WorkerName.[hash].js' } -} -``` - -### `inline` - -You can also inline the worker as a BLOB with the `inline` parameter - -**webpack.config.js** -```js -{ - loader: 'worker-loader', - options: { inline: true } -} -``` - -> ℹ️ Inline mode will also create chunks for browsers without support for inline workers, to disable this behavior just set `fallback` parameter as `false` - -**webpack.config.js** -```js -{ - loader: 'worker-loader' - options: { inline: true, fallback: false } -} -``` - -### `fallback` - -Require a fallback for non-worker supporting environments - -**webpack.config.js** -```js -{ - loader: 'worker-loader' - options: { fallback: false } -} -``` - -## Examples - -The worker file can import dependencies just like any other file - -**Worker.js** -```js -const _ = require('lodash') - -const obj = { foo: 'foo' } - -_.has(obj, 'foo') - -// Post data to parent thread -self.postMessage({ foo: 'foo' }) - -// Respond to message from parent thread -self.addEventListener('message', (event) => console.log(event)) -``` - -### `Integrating with ES2015 Modules` - -> ℹ️ You can even use ES2015 Modules if you have the [`babel-loader`](https://github.com/babel/babel-loader) configured. - -**Worker.js** -```js -import _ from 'lodash' - -const obj = { foo: 'foo' } - -_.has(obj, 'foo') - -// Post data to parent thread -self.postMessage({ foo: 'foo' }) - -// Respond to message from parent thread -self.addEventListener('message', (event) => console.log(event)) -``` - -### `Integrating with TypeScript` - -To integrate with TypeScript, you will need to define a custom module for the exports of your worker - -**typings/custom.d.ts** -```ts -declare module "worker-loader!*" { - class WebpackWorker extends Worker { - constructor(); - } - - export = WebpackWorker; -} -``` - -**Worker.ts** -```ts -const ctx: Worker = self as any; - -// Post data to parent thread -ctx.postMessage({ foo: "foo" }); - -// Respond to message from parent thread -ctx.addEventListener("message", (event) => console.log(event)); -``` - -**App.ts** -```ts -import MyWorker = require("worker-loader!./Worker"); - -const worker = new MyWorker(); - -worker.postMessage({ a: 1 }); -worker.onmessage = (event) => {}; - -worker.addEventListener("message", (event) => {}); -``` - -## Maintainers - - - - - - - - - - - -
- - - -
- Bogdan Chadkin -
- - -
- Juho Vepsäläinen -
-
- - -
- Joshua Wiens -
-
- - -
- Michael Ciniawsky -
-
- - -
- Alexander Krasnoyarov -
-
- - -[npm]: https://img.shields.io/npm/v/worker-loader.svg -[npm-url]: https://npmjs.com/package/worker-loader - -[node]: https://img.shields.io/node/v/cache-loader.svg -[node-url]: https://nodejs.org - -[deps]: https://david-dm.org/webpack-contrib/worker-loader.svg -[deps-url]: https://david-dm.org/webpack-contrib/worker-loader - -[test]: http://img.shields.io/travis/webpack-contrib/worker-loader.svg -[test-url]: https://travis-ci.org/webpack-contrib/worker-loader - -[cover]: https://codecov.io/gh/webpack-contrib/cache-loader/branch/master/graph/badge.svg -[cover-url]: https://codecov.io/gh/webpack-contrib/cache-loader - -[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg -[chat-url]: https://gitter.im/webpack/webpack - -*** - -> 原文:https://webpack.js.org/loaders/worker-loader/ +--- +title: worker-loader +source: https://raw.githubusercontent.com/webpack-contrib/worker-loader/master/README.md +edit: https://github.com/webpack-contrib/worker-loader/edit/master/README.md +repo: https://github.com/webpack-contrib/worker-loader +--- +This loader registers the script as Web Worker + + +## 安装 + +```bash +npm i -D worker-loader +``` + +## 用法 + +## + +**App.js** +```js +import Worker from 'worker-loader!./Worker.js'; +``` + +### `Config` + +**webpack.config.js** +```js +{ + module: { + rules: [ + { + test: /\.worker\.js$/, + use: { loader: 'worker-loader' } + } + ] + } +} +``` + +**App.js** +```js +import Worker from './file.worker.js'; + +const worker = new Worker(); + +worker.postMessage({ a: 1 }); +worker.onmessage = function (event) {}; + +worker.addEventListener("message", function (event) {}); +``` + +## Options + +|Name|Type|Default|Description| +|:--:|:--:|:-----:|:----------| +|[**`name`**](#name)|`{String}`|`[hash].worker.js`|Set a custom name for the output script| +|[**`inline`**](#inline)|`{Boolean}`|`false`|Inline the worker as a BLOB| +|[**`fallback`**](#fallback)|`{Boolean}`|`false`|Require a fallback for non-worker supporting environments| +|[**`publicPath`**](#publicPath)|`{String}`|`null`|Override the path from which worker scripts are downloaded| + +### `name` + +To set a custom name for the output script, use the `name` parameter. The name may contain the string `[hash]`, which will be replaced with a content dependent hash for caching purposes + +*webpack.config.js** +```js +{ + loader: 'worker-loader', + options: { name: 'WorkerName.[hash].js' } +} +``` + +### `inline` + +You can also inline the worker as a BLOB with the `inline` parameter + +**webpack.config.js** +```js +{ + loader: 'worker-loader', + options: { inline: true } +} +``` + +> ℹ️ Inline mode will also create chunks for browsers without support for inline workers, to disable this behavior just set `fallback` parameter as `false` + +**webpack.config.js** +```js +{ + loader: 'worker-loader' + options: { inline: true, fallback: false } +} +``` + +### `fallback` + +Require a fallback for non-worker supporting environments + +**webpack.config.js** +```js +{ + loader: 'worker-loader' + options: { fallback: false } +} +``` + +### `publicPath` + +Overrides the path from which worker scripts are downloaded. If not specified, the same public path used for other +webpack assets is used + +**webpack.config.js** +```js +{ + loader: 'worker-loader' + options: { publicPath: '/scripts/workers/' } +} +``` + +## Examples + +The worker file can import dependencies just like any other file + +**Worker.js** +```js +const _ = require('lodash') + +const obj = { foo: 'foo' } + +_.has(obj, 'foo') + +// Post data to parent thread +self.postMessage({ foo: 'foo' }) + +// Respond to message from parent thread +self.addEventListener('message', (event) => console.log(event)) +``` + +### `Integrating with ES2015 Modules` + +> ℹ️ You can even use ES2015 Modules if you have the [`babel-loader`](https://github.com/babel/babel-loader) configured. + +**Worker.js** +```js +import _ from 'lodash' + +const obj = { foo: 'foo' } + +_.has(obj, 'foo') + +// Post data to parent thread +self.postMessage({ foo: 'foo' }) + +// Respond to message from parent thread +self.addEventListener('message', (event) => console.log(event)) +``` + +### `Integrating with TypeScript` + +To integrate with TypeScript, you will need to define a custom module for the exports of your worker + +**typings/custom.d.ts** +```ts +declare module "worker-loader!*" { + class WebpackWorker extends Worker { + constructor(); + } + + export = WebpackWorker; +} +``` + +**Worker.ts** +```ts +const ctx: Worker = self as any; + +// Post data to parent thread +ctx.postMessage({ foo: "foo" }); + +// Respond to message from parent thread +ctx.addEventListener("message", (event) => console.log(event)); +``` + +**App.ts** +```ts +import Worker = require("worker-loader!./Worker"); + +const worker = new Worker(); + +worker.postMessage({ a: 1 }); +worker.onmessage = (event) => {}; + +worker.addEventListener("message", (event) => {}); +``` + +### `Cross-Origin Policy` + +[`WebWorkers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) are restricted by a [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy), so if your `webpack` assets are not being served from the same origin as your application, their download may be blocked by your browser. This scenario can commonly occur if you are hosting your assets under a CDN domain. Even downloads from the `webpack-dev-server` could be blocked. There are two workarounds + +Firstly, you can inline the worker as a blob instead of downloading it as an external script via the [`inline`](#inline) parameter + +**App.js** +```js +import Worker from './file.worker.js'; +``` + +**webpack.config.js** +```js +{ + loader: 'worker-loader' + options: { inline: true } +} +``` + +Secondly, you may override the base download URL for your worker script via the [`publicPath`](#publicpath) option + +**App.js** +```js +// This will cause the worker to be downloaded from `/workers/file.worker.js` +import Worker from './file.worker.js'; +``` + +**webpack.config.js** +```js +{ + loader: 'worker-loader' + options: { publicPath: '/workers/' } +} +``` + +## Maintainers + + + + + + + + + + + +
+ + + +
+ Bogdan Chadkin +
+ + +
+ Juho Vepsäläinen +
+
+ + +
+ Joshua Wiens +
+
+ + +
+ Michael Ciniawsky +
+
+ + +
+ Alexander Krasnoyarov +
+
+ + +[npm]: https://img.shields.io/npm/v/worker-loader.svg +[npm-url]: https://npmjs.com/package/worker-loader + +[node]: https://img.shields.io/node/v/cache-loader.svg +[node-url]: https://nodejs.org + +[deps]: https://david-dm.org/webpack-contrib/worker-loader.svg +[deps-url]: https://david-dm.org/webpack-contrib/worker-loader + +[test]: http://img.shields.io/travis/webpack-contrib/worker-loader.svg +[test-url]: https://travis-ci.org/webpack-contrib/worker-loader + +[cover]: https://codecov.io/gh/webpack-contrib/cache-loader/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack-contrib/cache-loader + +[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg +[chat-url]: https://gitter.im/webpack/webpack + +*** + +> 原文:https://webpack.js.org/loaders/worker-loader/ diff --git a/src/content/plugins/babel-minify-webpack-plugin.md b/src/content/plugins/babel-minify-webpack-plugin.md index a9caa4f09769..962b18288976 100644 --- a/src/content/plugins/babel-minify-webpack-plugin.md +++ b/src/content/plugins/babel-minify-webpack-plugin.md @@ -47,10 +47,10 @@ module.exports = { 你也可以在webpack中使用[babel-loader](https://github.com/babel/babel-loader),引入 `minify` [作为一个预设](https://github.com/babel/minify#babel-preset)并且应该运行的更快 - 因为 `babel-minify` 将运行在更小的文件。但是,这个插件为什么还存在呢? -+ webpack loader对单个文件进行操作,并且minify preset作为一个webpack loader将会把每个文件视为在浏览器全局范围内直接执行(默认情况下),并且不会优化顶级作用域内的某些内容。要在文件的顶级作用域内进行优化,请在minifyOptions中设置 `topLevel:true`。 -+ 当你排除 `node_modules` 不通过babel-loader运行时,babel-minify优化不会应用于被排除的文件,因为它们不会通过minifier。 -+ 当您使用带有webpack的babel-loader时,由webpack为模块系统生成的代码不会通过loader,并且不会通过babel-minify进行优化。 -+ 一个webpack插件可以在整个chunk / bundle输出上运行,并且可以优化整个bundle,你可以看到一些细微的输出差异。但是,由于文件大小通常非常大,所以会慢很多。所以这里有[一个想法](https://github.com/webpack-contrib/babel-minify-webpack-plugin/issues/8)——我们可以将一些优化作为loader的一部分,并在插件中进行一些优化。 ++ webpack loader 对单个文件进行操作,并且 minify preset 作为一个 webpack loader将会把每个文件视为在浏览器全局范围内直接执行(默认情况下),并且不会优化顶级作用域内的某些内容。要在文件的顶级作用域内进行优化,请在 minifyOptions 中设置 `mangle: { topLevel: true }`。 ++ 当你排除 `node_modules` 不通过 babel-loader 运行时,babel-minify 优化不会应用于被排除的文件,因为它们不会通过 minifier。 ++ 当您使用带有 webpack 的 babel-loader 时,由 webpack 为模块系统生成的代码不会通过 loader,并且不会通过 babel-minify 进行优化。 ++ 一个 webpack 插件可以在整个 chunk/bundle 输出上运行,并且可以优化整个bundle,你可以看到一些细微的输出差异。但是,由于文件大小通常非常大,所以会慢很多。所以这里有[一个想法](https://github.com/webpack-contrib/babel-minify-webpack-plugin/issues/8) - 我们可以将一些优化作为 loader 的一部分,并在插件中进行一些优化。 ## 维护人员 diff --git a/src/content/plugins/copy-webpack-plugin.md b/src/content/plugins/copy-webpack-plugin.md index 1b976296bc33..733f44e82310 100644 --- a/src/content/plugins/copy-webpack-plugin.md +++ b/src/content/plugins/copy-webpack-plugin.md @@ -19,6 +19,9 @@ npm install --save-dev copy-webpack-plugin A pattern looks like: `{ from: 'source', to: 'dest' }` +Or, in the simple case of just a `from` with the default destination, you can use a string primitive instead of an object: +`'source'` + ### | Name | Required | Default | Details | @@ -26,7 +29,7 @@ A pattern looks like: | `from` | Y | | _examples:_
'relative/file.txt'
'/absolute/file.txt'
'relative/dir'
'/absolute/dir'
'\*\*/\*'
{glob:'\*\*/\*', dot: true}

Globs accept [minimatch options](https://github.com/isaacs/minimatch) | | `to` | N | output root if `from` is file or dir

resolved glob path if `from` is glob | _examples:_
'relative/file.txt'
'/absolute/file.txt'
'relative/dir'
'/absolute/dir'
'relative/[name].[ext]'
'/absolute/[name].[ext]'

Templates are [file-loader patterns](/loaders/file-loader/) | | `toType` | N | **'file'** if `to` has extension or `from` is file

**'dir'** if `from` is directory, `to` has no extension or ends in '/'

**'template'** if `to` contains [a template pattern](/loaders/file-loader/) | | -| `context` | N | compiler.options.context | A path that determines how to interpret the `from` path | +| `context` | N | options.context \|\| compiler.options.context | A path that determines how to interpret the `from` path | | `flatten` | N | false | Removes all directory references and only copies file names

If files have the same name, the result is non-deterministic | | `ignore` | N | [] | Additional globs to ignore for this pattern | | `transform` | N | function(content, path) {
  return content;
} | Function that modifies file contents before writing to webpack | @@ -36,6 +39,7 @@ A pattern looks like: | Name | Default | Details | | ---- | ------- | ------- | +| `context` | compiler.options.context | A path that determines how to interpret the `from` path, shared for all patterns | | `ignore` | [] | Array of globs to ignore (applied to `from`) | | `copyUnmodified` | false | Copies files, regardless of modification when using watch or webpack-dev-server. All files are copied on first build, regardless of this option. | | `debug` | **'warning'** | _options:_
**'warning'** - only warnings
**'info'** or true - file location and read info
**'debug'** - very detailed debugging info @@ -59,6 +63,9 @@ module.exports = { // {output}/file.txt { from: 'from/file.txt' }, + // equivalent + 'from/file.txt', + // {output}/to/file.txt { from: 'from/file.txt', to: 'to/file.txt' }, diff --git a/src/content/plugins/module-concatenation-plugin.md b/src/content/plugins/module-concatenation-plugin.md index 492826b6bffe..e99707730726 100755 --- a/src/content/plugins/module-concatenation-plugin.md +++ b/src/content/plugins/module-concatenation-plugin.md @@ -15,7 +15,9 @@ related: new webpack.optimize.ModuleConcatenationPlugin() ``` -> 由于实现 ECMAScript 模块语法,作用域提升(Scope Hoisting)这个特定于此语法的功能才成为可能。`webpack` 可能会根据你正在使用的模块类型和[其他的情况](https://medium.com/webpack/webpack-freelancing-log-book-week-5-7-4764be3266f5),回退到普通打包。 +> 这种连结行为被称为“作用域提升(scope hoisting)”。 +> +> 由于实现 ECMAScript 模块语法,作用域提升(scope hoisting)这个特定于此语法的功能才成为可能。`webpack` 可能会根据你正在使用的模块类型和[其他的情况](https://medium.com/webpack/webpack-freelancing-log-book-week-5-7-4764be3266f5),回退到普通打包。 ## 绑定失败的优化[Optimization Bailouts] @@ -72,8 +74,8 @@ function tryToAdd(group, module) { if (!result) { return false; } - module.dependencies.forEach(depenency => { - tryToAdd(group, depenency); + module.dependencies.forEach(dependency => { + tryToAdd(group, dependency); }); group.merge(nextGroup); return true; diff --git a/src/content/plugins/uglifyjs-webpack-plugin.md b/src/content/plugins/uglifyjs-webpack-plugin.md index 8584266a6a5d..3bde630263df 100644 --- a/src/content/plugins/uglifyjs-webpack-plugin.md +++ b/src/content/plugins/uglifyjs-webpack-plugin.md @@ -6,9 +6,7 @@ repo: https://github.com/webpack-contrib/uglifyjs-webpack-plugin --- This plugin uses UglifyJS v3 (`uglify-es`) to minify your JavaScript -> ⚠️ This documentation is for the current beta. For latest stable, see [v0.4.6](https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/v0.4.6). - -> ℹ️ webpack contains the same plugin under `webpack.optimize.UglifyJsPlugin`. The documentation is valid apart from the installation instructions +> ℹ️ `webpack =< v3.0.0` currently contains [`v0.4.6`](https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/version-0.4) of this plugin under `webpack.optimize.UglifyJsPlugin` as an alias. For usage of the latest version (`v1.0.0`), please follow the instructions below. Aliasing `v1.0.0` as `webpack.optimize.UglifyJsPlugin` is scheduled for `webpack v4.0.0` ## 安装 @@ -31,18 +29,17 @@ module.exports = { ## 选项 -> ⚠️ 以下选项适用于最新的 beta 版本。如果您想查看 webpack 中内置的最新版本的选项,请参阅 [v0.4.6 文档](https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/v0.4.6)。 - |属性名称|类型|默认值|描述| |:--:|:--:|:-----:|:----------| |**`test`**|`{RegExp\|Array}`| /\.js($|\?)/i|测试匹配的文件| |**`include`**|`{RegExp\|Array}`|`undefined`|`包含`的文件| |**`exclude`**|`{RegExp\|Array}`|`undefined`|`排除`的文件。| +|**`cache`**|`{Boolean\|String}`|`false`|启用文件缓存| |**`parallel`**|`{Boolean\|Object}`|`false`|使用多进程并行运行和文件缓存来提高构建速度| |**`sourceMap`**|`{Boolean}`|`false`|使用 source map 将错误信息的位置映射到模块(这会减慢编译的速度) ⚠️ **`cheap-source-map` 选项不适用于此插件**| |**`uglifyOptions`**|`{Object}`|[`{...defaults}`](https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/master#uglifyoptions)|`uglify` [选项](https://github.com/mishoo/UglifyJS2/tree/harmony#minify-options)| |**`extractComments`**|`{Boolean\|RegExp\|Function<(node, comment) -> {Boolean\|Object}>}`|`false`|是否将注释提取到单独的文件,(查看[详细](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a(`webpack >= 2.3.0`)| -|**`warningsFilter`**|`{Function(source) -> {Boolean}}`|`undefined`|允许过滤 uglify 警告| +|**`warningsFilter`**|`{Function(source) -> {Boolean}}`|`() => true`|允许过滤 uglify 警告| ## @@ -50,7 +47,7 @@ module.exports = { ```js [ new UglifyJSPlugin({ - test: /\.js($|\?)/i + test: /\.js($|\?)/i }) ] ``` @@ -77,8 +74,39 @@ module.exports = { ] ``` +### `cache` + +#### `{Boolean}` + +**webpack.config.js** +```js +[ + new UglifyJSPlugin({ + cache: true + }) +] +``` + +Enable file caching. +Default path to cache directory: `node_modules/.cache/uglifyjs-webpack-plugin`. + +#### `{String}` + +**webpack.config.js** +```js +[ + new UglifyJSPlugin({ + cache: 'path/to/cache' + }) +] +``` + +Path to cache directory. + ### `parallel` +#### `{Boolean}` + **webpack.config.js** ```js [ @@ -88,23 +116,22 @@ module.exports = { ] ``` -|Name|Type|Default|Description| -|:--:|:--:|:-----:|:----------| -|**`cache`**|`{Boolean}`|`node_modules/.cache/uglifyjs-webpack-plugin`|Enable file caching| -|**`workers`**|`{Boolean\|Number}`|`os.cpus().length - 1`|Number of concurrent runs, default is the `maximum`| +Enable parallelization. +Default number of concurrent runs: `os.cpus().length - 1`. + +#### `{Number}` **webpack.config.js** ```js [ new UglifyJSPlugin({ - parallel: { - cache: true, - workers: 2 // for e.g - } + parallel: 4 }) ] ``` +Number of concurrent runs. + > ℹ️ Parallelization can speedup your build significantly and is therefore **highly recommended** ### `sourceMap` @@ -160,15 +187,15 @@ module.exports = { ### `extractComments` -**`{Boolean}`** +#### `{Boolean}` -All comments that normally would be preserved by the `comments` option will be moved to a separate file. If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE` +All comments that normally would be preserved by the `comments` option will be moved to a separate file. If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE`. -**`{RegExp|String}` or `{Function<(node, comment) -> {Boolean}>}`** +#### `{RegExp|String}` or `{Function<(node, comment) -> {Boolean}>}` All comments that match the given expression (resp. are evaluated to `true` by the function) will be extracted to the separate file. The `comments` option specifies whether the comment will be preserved, i.e. it is possible to preserve some comments (e.g. annotations) while extracting others or even preserving comments that have been extracted. -**`{Object}`** +#### `{Object}` |Name|Type|Default|Description| |:--:|:--:|:-----:|:----------|