使用WebPack在Web Worker中运行Angular 2应用 [英] Run Angular 2 app in web worker using WebPack

查看:43
本文介绍了使用WebPack在Web Worker中运行Angular 2应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Angular 2应用程序的整个执行转移到网络工作者,但是我发现现在所有可用的示例都在使用System.js,而我正在尝试使用基于WebPack的项目(使用angular-cli构建).

I'm trying to move the whole execution of an Angular 2 app to a web worker, but I've find out that all examples available right now are using System.js, and I'm trying to do so with a WebPack based project (built with angular-cli).

有没有人做过或有关于如何使用WebPack做到这一点的想法?

Has anyone done this or have an idea on how to do this with WebPack?

下面是我的main.ts引导文件:

Below is my main.ts bootstrap file:

import './polyfills.ts';


import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';


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

import {bootstrapWorkerUi} from '@angular/platform-webworker';
bootstrapWorkerUi('/app/loader.js');

我的loader.js看起来像这样:

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

platformWorkerAppDynamic().bootstrapModule(AppModule);

我的app.module.ts以此方式声明@NgModule:

import { NgModule } from '@angular/core';
import {WorkerAppModule} from '@angular/platform-webworker';


import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    WorkerAppModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
 export class AppModule { }

但是,当我运行它时,在loader.js:1中收到错误 Uncaught SyntaxError:Unexpected token import .

However, when I run it, I get the error Uncaught SyntaxError: Unexpected token import in loader.js:1.

问题似乎与webpack有关,正如Tamas Gegedus和MathMate所建议的那样,webworker端缺少@angular库的导入,因此下一步是修改webpack配置文件以提供所有必需的库给网络工作者.我会解决的.

The issue seems related with webpack and some lack of imports of @angular libs in the webworker side, as suggested by Tamas Gegedus and MathMate, so the next step is to modify the webpack config file in order to provide all the required libs to the webworker. I'll work on that.

----------- 更新 -----------

----------- UPDATE -----------

由于angular-cli无法提供对webpack.config.js文件的访问,因此我加入了我的文件,对代码进行了很少的更改,因此它可以正常工作.我在webpack配置文件中创建了第二个入口点,但出现错误 VM33:106 Uncaught ReferenceError:未定义窗口.

Since angular-cli do not provide access to webpack.config.js file, I've included mine, making little changes in code so it can work. I created the second entry point at webpack config file and I'm getting the error VM33:106 Uncaught ReferenceError: window is not defined.

Webpack配置文件如下:

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var helpers = require('./config/helpers');


module.exports = {
  entry: {
    'app': ['./src/polyfills.ts', './src/vendor.ts', './src/main.ts'],
    'webworker': ['./src/workerLoader.ts']
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  output: {
    path: helpers.root('dist'),
    publicPath: 'http://localhost:8080/',
    filename: '[name].js'
  },

  devtool: 'cheap-module-eval-source-map',

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader?tsconfig=./src/tsconfig.json', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      }
    ]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      excludeChunks: ['webworker']
    }),

    new ExtractTextPlugin('[name].css')
  ]
};

其中polyfills.ts和vendor.ts分别包括polyfills和角形库.

where polyfills.ts and vendor.ts include polyfills and angular libs respectively.

我创建了2个入口点,它们生成2个输出(app.js和webworker.js).

I've created 2 entry points, that generate 2 outputs (app.js and webworker.js).

对于HtmlWebpackPlugin,第一个包含在index.html文件中,而第二个则不包含.

With the HtmlWebpackPlugin, the first one is included in the index.html file, but not the second one.

包含index.html时,将调用 main.ts (包含在app.js中),并尝试使用webpack的第二个输出(webworker.js)引导Webworker.:

When index.html is included, main.ts (contained in app.js) is called and tries to bootstrap the webworker using the second output of webpack (webworker.js):

import {bootstrapWorkerUi} from '@angular/platform-webworker';
bootstrapWorkerUi('../webworker.js');

webworker.js是由webpack使用workerLoader.ts条目生成的,就像以前的loader.js一样,但其中包含一些导入.

webworker.js has been generated by webpack using workerLoader.ts entry, that is like previous loader.js, but including some imports.

WorkerLoader.ts文件如下:

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

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

platformWorkerAppDynamic().bootstrapModule(AppModule);

我知道生成了Web worker,如下图所示,但是如图所示,我收到错误 VM33:106 Uncaught ReferenceError:未定义窗口,并且除了index.html的正在加载"消息外,没有显示任何内容.

I know that the web worker is been generated, as shown in the following image, but as shown in the image, I get the error VM33:106 Uncaught ReferenceError: window is not defined, and nothing is displayed except the Loading message from index.html.

另一方面,我认为webpack配置还可以,因为如果在无webworker模式下以webpack运行应用程序,则可以正常工作.

On the other side, I think that the webpack config is OK because if running the app with webpack in NO webworker mode, it works fine.

现在,我认为此问题与Webworker引导程序有关,但我对此颇为困惑.

Right now I think that this issue is related with webworker bootstrap, but I'm quite stucked here.

任何帮助将不胜感激;)

Any help would be appreciated ;)

推荐答案

我终于解决了问题:)

注意::如果您已使用 Angular CLI 1.0 或更高版本生成项目,则现在可以使用其自己的webpack配置文件,并且这简化了整个过程. 检查在这种情况下的答案.

NOTE: if you have generated the project using Angular CLI 1.0 or higher, you can now use their own webpack config file, and that simplifies the whole process. Check this answer in that case.

使用自定义的webpack配置运行代码后,我意识到错误 VM33:106 Uncaught ReferenceError:窗口未定义是由 webpack-dev-server .

After running the code with my custom webpack config, I realized that the error VM33:106 Uncaught ReferenceError: window is not defined was caused by webpack-dev-server.

我通过以下方式解决了该问题:

I solved it by:

1-执行独立的Webpack构建

1 - doing a standalone webpack build

$: webpack --watch #this creates the bundes at myProject/dist

2-与其他开发服务器工具一起运行,例如 simplehttpserver

2 - running with another devserver tool like simplehttpserver

$: npm install simplehttpserver -g
$: simplehttpserver -p 8080 dist/ #as my webpack bundle is included in index.html using that port by default

瞧瞧,错误消失了,它简单地起作用了!

让我总结一下有关原始Angular-CLI项目的Webpack更改.

Let me summarize the webpack changes regarding the original Angular-CLI project.

由于angular-cli不提供对webpack.config.js文件的访问权限,并且自定义Webpack是使用Webworkers的关键,因此我加入了我的内容,对代码的更改很少.

As angular-cli do not provide access to webpack.config.js file and customizing webpack is key to use webworkers, I've included mine, making little changes in code.

Webpack配置文件如下:

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var helpers = require('./config/helpers');


module.exports = {
  entry: {
    'app': ['./src/polyfills.ts', './src/vendor.ts', './src/main.ts'],
    'webworker': ['./src/workerLoader.ts']
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  output: {
    path: helpers.root('dist'),
    publicPath: 'http://localhost:8080/',
    filename: '[name].js'
  },

  devtool: 'cheap-module-eval-source-map',

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader?tsconfig=./src/tsconfig.json', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      }
    ]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      excludeChunks: ['webworker']
    }),

    new ExtractTextPlugin('[name].css')
  ]
};

其中polyfills.ts和vendor.ts分别包括polyfills和角形库.

where polyfills.ts and vendor.ts include polyfills and angular libs respectively.

我创建了2个入口点,它们生成2个输出(app.js和webworker.js).

I've created 2 entry points, that generate 2 outputs (app.js and webworker.js).

对于HtmlWebpackPlugin,第一个包含在index.html文件中,而第二个则不包含.

With the HtmlWebpackPlugin, the first one is included in the index.html file, but not the second one.

包含index.html时,将调用 main.ts (包含在app.js中),并像这样自举Webworker :

When index.html is included, main.ts (contained in app.js) is called and bootstraps the webworker like this:

import {bootstrapWorkerUi} from '@angular/platform-webworker';
bootstrapWorkerUi('../webworker.js');

webworker.js是使用workerLoader.ts条目生成的Webpack代码.

webworker.js is the code webpack generated using workerLoader.ts entry.

WorkerLoader.ts文件如下:

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

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

platformWorkerAppDynamic().bootstrapModule(AppModule);

AppModule看起来像这样:

import { NgModule } from '@angular/core';
import {WorkerAppModule} from '@angular/platform-webworker';


import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    WorkerAppModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
 export class AppModule { }

为了更容易理解它们之间的差异,我创建了一个项目,该项目显示了如何在基于web worker的web工程中转换常规的angular 2项目.检查此仓库: https://github.com/kaikcreator/webWorkerFactorialExample

To make easier to understand the differences, I've created a project showing how to convert a regular angular 2 project in a web workers based one. Check this repo: https://github.com/kaikcreator/webWorkerFactorialExample

您将在master分支中看到单线程"代码,然后在 webWorkers分支中,进行更改以使用Web Worker运行代码.

You'll see in master branch the "single thread" code, and in webWorkers branch, the changes to run code using web workers.

这篇关于使用WebPack在Web Worker中运行Angular 2应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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