- webpack概述
- 入口起点(Entry Points)
- 输出(Output)
- 模块(Mode)
- 加载器(Loaders)
- 插件(Plugins)
- 配置(Configuration)
- 模块(Modules)
- 模块解析(Module Resolution)
- 依赖图表(Dependency Graph)
- 文件清单(Manifest)
- 构建目标(Targets)
- 模块热替换(Hot Module Replacement)
- 第二部分:配置
- 使用不同语言进行配置(Configuration Languages)
- 多种配置类型
- 入口和上下文(Entry and Context)
- 输出(Output)
- 模块(Module)
- 解析(Resolve)
- 插件(Plugins)
- 开发中 Server(DevServer)
- 开发工具(Devtool)
- 构建目标(Targets)
- Watch 和 WatchOptions
- 外部扩展(Externals)
- 性能(Performance)
- Node
- 统计(Stats)
- 其它选项(Other Options)
- 第三部分:API
- 命令行接口(CLI)
- 包含统计数据的文件(stats data)
- Node.js API
- 模块热替换(Hot Module Replacement)
- 加载器 API
- 模块方法(module methods)
- 模块变量(module variables)
- Plugin API
- compiler 钩子
- compilation 钩子
- resolver
- parser
- 第四部分:指南
- 安装
- 起步
- 管理资源
- 管理输出
- 开发
- 模块热替换
- Tree shaking
- 生产环境构建
- 代码拆分(Code Splitting)
- 懒加载(Lazy Loading)
- 缓存(Caching)
- 创建库 (Library)
- Shimming
- 渐进式网络应用程序
- TypeScript
- 迁移到新版本
- 使用环境变量
- 构建性能
- 内容安全策略
- 开发 - Vagrant
- 管理依赖
- Public Path(公共路径)
- 集成(Integrations)
- 第五部分:加载器
- babel-loader
- yaml-frontmatter-loader
- cache-loader
- coffee-loader
- coffee-redux-loader
- coverjs-loader
- css-loader
- exports-loader
- expose-loader
- extract-loader
- file-loader
- gzip-loader
- html-loader
- i18n-loader
- imports-loader
- istanbul-instrumenter-loader
- jshint-loader
- json-loader
- json5-loader
- less-loader
- bundle-loader
- multi-loader
- node-loader
- null-loader
- polymer-webpack-loader
- postcss-loader
- raw-loader
- react-proxy-loader
- restyle-loader
- sass-loader
- script-loader
- source-map-loader
- style-loader
- svg-inline-loader
- thread-loader
- transform-loader
- url-loader
- val-loader
- worker-loader
- mocha-loader
- 第六部分:插件
- AggressiveSplittingPlugin
- ZopfliWebpackPlugin
- BannerPlugin
- ClosureWebpackPlugin
- CommonsChunkPlugin
- ComponentWebpackPlugin
- CompressionWebpackPlugin
- ContextReplacementPlugin
- CopyWebpackPlugin
- DefinePlugin
- DllPlugin
- EnvironmentPlugin
- EvalSourceMapDevToolPlugin
- ExtractTextWebpackPlugin
- HashedModuleIdsPlugin
- HotModuleReplacementPlugin
- HtmlWebpackPlugin
- BabelMinifyWebpackPlugin
- IgnorePlugin
- LoaderOptionsPlugin
- MinChunkSizePlugin
- ModuleConcatenationPlugin
- NamedModulesPlugin
- NormalModuleReplacementPlugin
- NpmInstallWebpackPlugin
- PrefetchPlugin
- ProfilingPlugin
- ProvidePlugin
- SourceMapDevToolPlugin
- SplitChunksPlugin
- UglifyjsWebpackPlugin
- WatchIgnorePlugin
- I18nWebpackPlugin
worker-loader
This loader registers the script as Web Worker
安装
npm i -D worker-loader
用法
App.js
import Worker from 'worker-loader!./Worker.js';
Config
webpack.config.js
{
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
}
App.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 |
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*
{
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
{
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 asfalse
webpack.config.js
{
loader: 'worker-loader'
options: { inline: true, fallback: false }
}
fallback
Require a fallback for non-worker supporting environments
webpack.config.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
{
loader: 'worker-loader'
options: { publicPath: '/scripts/workers/' }
}
Examples
The worker file can import dependencies just like any other file
Worker.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
configured.
Worker.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
declare module "worker-loader!*" {
class WebpackWorker extends Worker {
constructor();
}
export = WebpackWorker;
}
Worker.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
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
are restricted by a 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
parameter
App.js
import Worker from './file.worker.js';
webpack.config.js
{
loader: 'worker-loader'
options: { inline: true }
}
Secondly, you may override the base download URL for your worker script via the publicPath
option
App.js
// This will cause the worker to be downloaded from `/workers/file.worker.js`
import Worker from './file.worker.js';
webpack.config.js
{
loader: 'worker-loader'
options: { publicPath: '/workers/' }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论