Angular CLI使用Web Workers生成的应用程序 [英] Angular CLI generated app with Web Workers

查看:83
本文介绍了Angular CLI使用Web Workers生成的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Angular文档,您可以找到几个引用将您的整个Angular应用引导到Web Worker内,这样您的UI不会被大量的JS使用所阻塞.

Reading the Angular Documentation, you can find several references to bootstrap your whole Angular app inside a Web Worker, so your UI won't get blocked by heavy JS usage.

但是,目前尚无有关此操作的官方信息,只有Angular Doc中有此信息.是这是一项实验性功能.

However, at this moment there's no official information on how to do that, and the only info in the Angular Doc. is that this is an experimental feature.

我如何使用这种方法来利用Angular中的Web工作者?

How can I use this approach to take advantage of web workers in Angular?

推荐答案

对于Angular 7,请参见下面的答案.

我花了很多时间弄清楚该怎么做,所以我希望

I spent a lot of time to figure out how to do it, so I hope this can help someone.

我假设您有一个使用Angular CLI 1.0或更高版本生成的Angular项目(版本2或4).

I’m assuming that you have an Angular project (version 2 or 4) generated with Angular CLI 1.0 or higher.

使用CLI生成项目并非必须遵循此步骤,但是我将与webpack文件相关的说明是基于CLI webpack配置的.

It is not mandatory to generate the project with CLI to follow this steps, but the instructions I'll give related with the webpack file, are be based on the CLI webpack config.

自Angular CLI v1.0起,有了弹出"功能,可让您提取webpack配置文件并根据需要进行操作.

Since Angular CLI v1.0, there’s the "eject" feature, that allows you to extract the webpack config file and manipulate it as you wish.

  • 运行ng eject,以便Angular CLI生成 webpack.config.js 文件.

  • Run ng eject so Angular CLI generates the webpack.config.js file.

运行npm install,以便满足CLI生成的新依赖项

Run npm install so the new dependencies generated by CLI are satisfied

运行npm install --save @angular/platform-webworker @angular/platform-webworker-dynamic

在app.module.ts文件中用WorkerAppModule替换BrowserModule.您还需要更新import语句才能使用@angular/platform-webworker库.

Replace BrowserModule by WorkerAppModule in the app.module.ts file. You’ll also need to update the import statement in order to use @angular/platform-webworker library.

//src/app/app.module.ts

import { WorkerAppModule } from '@angular/platform-webworker';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
//...other imports...

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    WorkerAppModule,
    //...other modules...
  ],
  providers: [/*...providers...*/],
  bootstrap: [AppComponent]
})
export class AppModule { }

将引导程序替换为:bootstrapWorkerUI(也更新导入).

Replace bootstrap process with: bootstrapWorkerUI (update also the import).

您需要将URL与定义了网络工作者的文件一起传递.使用名为webworker.bundle.js的文件,请放心,我们将尽快创建该文件.

You’ll need to pass a URL with the file where the web worker is defined. Use a file called webworker.bundle.js, don’t worry, we will create this file soon.

//main.ts

import { enableProdMode } from '@angular/core';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

bootstrapWorkerUi('webworker.bundle.js');

  • 创建一个新文件src/workerLoader.ts .
  • 由于您的Web Worker将是一个包含所有必需内容的文件,因此您需要包括polyfills.ts@angular/core@angular/common软件包.在接下来的步骤中,您将更新Webpack以便转换并使用结果构建一个包.
  • 导入platformWorkerAppDynamic
  • 导入AppModule(从 main.ts 中删除导入),并使用此platformWorkerAppDynamic平台对其进行引导.
  • Create a new file src/workerLoader.ts.
  • As your Web Worker will be a single file containing all the required stuff, you need to include polyfills.ts, @angular/core, and @angular/common packages. On next steps, you will update Webpack in order to transpile and build a bundle with the result.
  • Import platformWorkerAppDynamic
  • Import the AppModule (remove the import from main.ts) and bootstrap it using this platformWorkerAppDynamic platform.

// workerLoader.ts

import 'polyfills.ts';
import '@angular/core';
import '@angular/common';

import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic';
import { AppModule } from './app/app.module';

platformWorkerAppDynamic().bootstrapModule(AppModule);

webpack自动生成的配置文件很长,但是您只需要集中注意以下几点:

The webpack auto generated config file is quite long, but you’ll just need to center your attention in the following things:

  • 为我们的workerLoader.ts文件添加webworker 入口点.如果查看输出,您会看到它在所有块上附加了bundle.js前缀.这就是为什么在引导步骤中我们使用webworker.bundle.js

  • Add a webworkerentry point for our workerLoader.ts file. If you look at the output, you’ll see that it attaches a bundle.js prefix to all chunks. That’s why during bootstrap step we have used webworker.bundle.js

转到 HtmlWebpackPlugin 并排除webworker入口点,因此生成的Web Worker文件不包括在index.html文件中.

Go to HtmlWebpackPlugin and exclude the webworker entry point, so the generated Web Worker file is not included in the index.html file.

转到 CommonChunksPlugin ,并为inline通用块设置显式设置条目块,以防止包含webworker.

Go to CommonChunksPlugin, and for the inline common chunk, set the entry chunks explicitely to prevent webworker to be included.

转到 AotPlugin 并明确设置entryModule

// webpack.config.js

//...some stuff...
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CommonsChunkPlugin } = require('webpack').optimize;
const { AotPlugin } = require('@ngtools/webpack');
//...some stuff...

module.exports = {
  //...some stuff...
  "entry": {
    "main": [
      "./src/main.ts"
    ],
    "polyfills": [
      "./src/polyfills.ts"
    ],
    "styles": [
      "./src/styles.css"
    ],
    "webworker": [
      "./src/workerLoader.ts"
    ]
  },
  "output": {
    "path": path.join(process.cwd(), "dist"),
    "filename": "[name].bundle.js",
    "chunkFilename": "[id].chunk.js"
  },
  "module": { /*...a lot of stuff...*/ },
  "plugins": [
    //...some stuff...
    new HtmlWebpackPlugin({
      //...some stuff...
      "excludeChunks": [
        "webworker"
      ],
      //...some more stuff...
    }),
    new BaseHrefWebpackPlugin({}),
    new CommonsChunkPlugin({
      "name": "inline",
      "minChunks": null,
      "chunks": [
        "main",
        "polyfills",
        "styles"
      ]
    }),
    //...some stuff...
    new AotPlugin({
      "mainPath": "main.ts",
      "entryModule": "app/app.module#AppModule",
      //...some stuff...
    })
  ],
  //...some more stuff...
};

如果您正确地遵循了前面的步骤,那么现在只需要编译代码并尝试结果即可.

If you have followed correctly the previous steps, now you only need to compile the code and try the results.

运行npm start

您的Angular应用程序的所有逻辑都应在WebWorker内部运行,从而使UI更加流畅.

All the logic of your Angular app should be running inside a WebWorker, causing the UI to be more fluent.

npm start运行 webpack-dev服务器,并且Web工作者在控制台日志上抛出错误消息时出现了某种问题.无论如何,网络工作者似乎运行良好. 如果您使用webpack命令编译该应用程序并从任何

npm start runs the webpack-dev server, and it has some kind of problem with webworkers throwing an error message on console log. Anyway, the webworker seems to run fine. If you compile the app using webpack command and serve it from any http server like simplehttpserver, the error goes away ;)

您可以从您还可以在此处观看实时演示,以查看差异使用Web Worker之间的差异

You can also watch here a live demo, to check out differences between using Web Workers or not

这篇关于Angular CLI使用Web Workers生成的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆