Angular-angular6中Web工作者的Webpack配置

时间:2018-08-14 08:43:34

标签: angular webpack angular-cli angular6 web-worker

我试图按照here

中的说明在Web Worker中运行我的angular6 Web应用程序

由于angular6中缺少ng eject,因此我使用this创建了一个自定义的webpack配置文件。

workerLoader.ts

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

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

platformWorkerAppDynamic().bootstrapModule(AppModule);

main.ts

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

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



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


bootstrapWorkerUi('webworker.chunk.js',WORKER_UI_LOCATION_PROVIDERS);

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import {
  WorkerAppModule,
  WORKER_APP_LOCATION_PROVIDERS,
  WORKER_UI_LOCATION_PROVIDERS
} from '@angular/platform-webworker';
import { APP_BASE_HREF } from '@angular/common'

@NgModule({
  declarations: [
    AppComponent,
   // some components
  ],
  imports: [
    BrowserModule,
    //some imports
    WorkerAppModule,

  ],
  providers: [
    {
      provide: APP_BASE_HREF,
      useValue: '/'
    },
    WORKER_APP_LOCATION_PROVIDERS
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const { AotPlugin } = require('@ngtools/webpack');


module.exports = {
    "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"
},

 optimization: {
     splitChunks: {
         cacheGroups: {
             commons: {
                 test: /[\\/]node_modules[\\/]/,
                 name: 'vendor',
                 chunks: 'all'
             }
         }
     }
 },

}

问题是进入浏览器后,出现错误webworker.chunk.js:1 Uncaught ReferenceError: window is not defined,造成此错误的行是
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["webworker"],{

我找到相同的question,但对我不起作用。

如何解决问题?

更新
我的问题被标记为可能重复,但我自己提到了这个问题,并强调这对我不起作用。

更新
AFAIK,Web工作人员无法访问诸如window之类的全局变量,并且由于某种原因要在Web Worker中访问window,因此该错误有点奇怪。我认为webpack配置文件中的配置错误是错误的原因。 the error image

1 个答案:

答案 0 :(得分:0)

我遇到了同样的错误,我通过在angular.json中的customWebpackConfig中添加以下选项来解决了这个问题:

"mergeStrategies": {"optimization":"replace"}

我希望对您有帮助

请参阅related gitHub issue