未定义的“未捕获的错误”窗口尝试在Webworker中运行angular App时出现问题

时间:2019-04-12 07:05:32

标签: node.js webpack angular5

Uncaught error window not defined when trying to host the application inside a webworker.

The webpack doesnt accept the globalObject property in output, secondly my webworker doesnt has any refernce to window only when I run the application using webpack dev server the inline.bundle.js is formed which contains reference to window.

1. I have configured my webpack as per the below code .
2. Bootstrapped my application as per the below code.
3. the webpack has been configured with all the required configurations
4. the devserver config has been used to use proxies.
5. globalObject in output doesnt work eg: output {"globalObject":this}
6. window:self doesnt work in webpack file.
  

lorem ipsum表示印刷和排版行业的伪文本。自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。它在1960年代流行,发行了包含Lorem Ipsum段落的Letraset表格,最近又发布了包括Alres PageMaker在内的桌面发行软件,包括Lorem Ipsum的版本。   暗示印刷和排版行业的伪文本。自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。它在1960年代开始流行,其中包含Lereset Ipsum段落的Letraset表发行,最近又发行了包括Lorem Ipsum版本的台式出版软件Aldus PageMaker。这意味着印刷和排版行业中的虚拟文本。自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。它在1960年代开始流行,其中包含Lereset Ipsum段落的Letraset表发行,最近又发行了包括Lorem Ipsum版本的台式出版软件Aldus PageMaker。这意味着印刷和排版行业中的虚拟文本。自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。它在1960年代开始流行,发布了包含Lorem Ipsum段落的Letraset工作表,最近又发布了包括Alres PageMaker在内的桌面发行软件,包括Lorem Ipsum的版本。

main.ts:主文件

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import { ApplicationRef } from "@angular/core";
import { enableDebugTools } from "@angular/platform-browser";
import { enableProdMode } from '@angular/core';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

enableProdMode();

//platformBrowserDynamic().bootstrapModule(AppModule);
bootstrapWorkerUi('webworker.bundle.js');
// platformBrowserDynamic().bootstrapModule(AppModule)
//   .then(moduleRef => {
//    const applicationRef = moduleRef['injector'].get(ApplicationRef);
//    const componentRef = applicationRef.components[0];
//     // allows to run `ng.profiler.timeChangeDetection();`
//     enableDebugTools(componentRef);
//   })
//   .catch(err => console.log(err));

workerLoader.ts:workerLoader

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

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


platformWorkerAppDynamic().bootstrapModule(AppModule);

webpack.config.js:Webpack文件

const fs = require('fs');
const path = require('path');
const resolve = require('path').resolve;
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const rxPaths = require('rxjs/_esm5/path-mapping');
const autoprefixer = require('autoprefixer');
const postcssUrl = require('postcss-url');
const postcssImports = require('postcss-import');

const { NoEmitOnErrorsPlugin, SourceMapDevToolPlugin, NamedModulesPlugin } = require('webpack');
const { ScriptsWebpackPlugin, NamedLazyChunksWebpackPlugin, BaseHrefWebpackPlugin, PostcssCliResources } = require('@angular/cli/plugins/webpack');
const { CommonsChunkPlugin } = require('webpack').optimize;
const { AngularCompilerPlugin } = require('@ngtools/webpack');

const nodeModules = path.join(process.cwd(), 'node_modules');
const realNodeModules = fs.realpathSync(nodeModules);
const genDirNodeModules = path.join(process.cwd(), 'src/main/ui', '$$_gendir', 'node_modules');
const entryPoints = ["inline", "polyfills", "sw-register", "styles", "scripts", "vendor", "main"];
const hashFormat = { "chunk": "", "extract": "", "file": ".[hash:20]", "script": "" };
const baseHref = "";
const deployUrl = "";
const projectRoot = process.cwd();
const maximumInlineSize = 10;
const postcssPlugins = function (loader) {
    return [
        postcssImports({
            resolve: (url, context) => {
                return new Promise((resolve, reject) => {
                    let hadTilde = false;
                    if (url && url.startsWith('~')) {
                        url = url.substr(1);
                        hadTilde = true;
                    }
                    loader.resolve(context, (hadTilde ? '' : './') + url, (err, result) => {
                        if (err) {
                            if (hadTilde) {
                                reject(err);
                                return;
                            }
                            loader.resolve(context, url, (err, result) => {
                                if (err) {
                                    reject(err);
                                }
                                else {
                                    resolve(result);
                                }
                            });
                        }
                        else {
                            resolve(result);
                        }
                    });
                });
            },
            load: (filename) => {
                return new Promise((resolve, reject) => {
                    loader.fs.readFile(filename, (err, data) => {
                        if (err) {
                            reject(err);
                            return;
                        }
                        const content = data.toString();
                        resolve(content);
                    });
                });
            }
        }),
        postcssUrl({
            filter: ({ url }) => url.startsWith('~'),
            url: ({ url }) => {
                const fullPath = path.join(projectRoot, 'node_modules', url.substr(1));
                return path.relative(loader.context, fullPath).replace(/\\/g, '/');
            }
        }),
        postcssUrl([
            {
                // Only convert root relative URLs, which CSS-Loader won't process into require().
                filter: ({ url }) => url.startsWith('/') && !url.startsWith('//'),
                url: ({ url }) => {
                    if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) {
                        // If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is.
                        return `${deployUrl.replace(/\/$/, '')}${url}`;
                    }
                    else if (baseHref.match(/:\/\//)) {
                        // If baseHref contains a scheme, include it as is.
                        return baseHref.replace(/\/$/, '') +
                            `/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
                    }
                    else {
                        // Join together base-href, deploy-url and the original URL.
                        // Also dedupe multiple slashes into single ones.
                        return `/${baseHref}/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
                    }
                }
            },
            {
                // TODO: inline .cur if not supporting IE (use browserslist to check)
                filter: (asset) => {
                    return maximumInlineSize > 0 && !asset.hash && !asset.absolutePath.endsWith('.cur');
                },
                url: 'inline',
                // NOTE: maxSize is in KB
                maxSize: maximumInlineSize,
                fallback: 'rebase',
            },
            { url: 'rebase' },
        ]),
        PostcssCliResources({
            deployUrl: loader.loaders[loader.loaderIndex].options.ident == 'extracted' ? '' : deployUrl,
            loader,
            filename: `[name]${hashFormat.file}.[ext]`,
        }),
        autoprefixer({ grid: true }),
    ];
};




module.exports = {
    "resolve": {
        "extensions": [
            ".ts",
            ".js"
        ],
        "symlinks": true,
        "modules": [
            "./src\\main\\ui",
            "./node_modules"
        ],
        "alias": rxPaths(),
        "mainFields": [
            "browser",
            "module",
            "main"
        ]
    },
    "resolveLoader": {
        "modules": [
            "./node_modules"
        ],
        "alias": rxPaths()
    },
    "entry": {
        "main": [
            "./src\\main\\ui\\app2\\main.ts"
        ],
        "polyfills": [
            "./src\\main\\ui\\polyfills.ts"
        ],
        "styles": [
            "./src\\main\\ui\\scss\\styles.scss"
        ],
        "webworker": [
            "./src\\main\\ui\\app2\\workerLoader.ts"
        ]
    },
    "output": {
        //"path": path.join(process.cwd(),'/xxxxx'),
        //"path": path.join(process.cwd(), "src\\main\\ui\\xxxxx"),
        "publicPath": "/xxxxx/",
        "path": resolve('dist'),
        "filename": "[name].bundle.js",
        "chunkFilename": "[id].chunk.js",
        "crossOriginLoading": false
    },
    "module": {
        "rules": [
            {
                "test": /\.html$/,
                "loader": "raw-loader"
            },
            {
                "test": /\.(eot|svg|cur)$/,
                "loader": "file-loader",
                "options": {
                    "name": "[name].[hash:20].[ext]",
                    "limit": 10000
                }
            },
            {
                "test": /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
                "loader": "url-loader",
                "options": {
                    "name": "[name].[hash:20].[ext]",
                    "limit": 10000
                }
            },
            {
                "exclude": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.css$/,
                "use": [
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    }
                ]
            },
            {
                "exclude": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.scss$|\.sass$/,
                "use": [
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "sass-loader",
                        "options": {
                            "sourceMap": true,
                            "precision": 8,
                            "includePaths": [
                                "C:\\workspace\\xxxxxxxxxx\\xxxxxxxxxx-ui\\src\\main\\ui\\src\\main\\ui"
                            ]
                        }
                    }
                ]
            },
            {
                "exclude": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.less$/,
                "use": [
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "less-loader",
                        "options": {
                            "sourceMap": true,
                            "paths": [
                                "C:\\workspace\\xxxxxxxxxx\\xxxxxxxxxx-ui\\src\\main\\ui\\src\\main\\ui"
                            ]
                        }
                    }
                ]
            },
            {
                "exclude": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.styl$/,
                "use": [
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "stylus-loader",
                        "options": {
                            "sourceMap": true,
                            "paths": [
                                "C:\\workspace\\xxxxxxxxxx\\xxxxxxxxxx-ui\\src\\main\\ui\\src\\main\\ui"
                            ]
                        }
                    }
                ]
            },
            {
                "include": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.css$/,
                "use": [
                    "style-loader",
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    }
                ]
            },
            {
                "include": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.scss$|\.sass$/,
                "use": [
                    "style-loader",
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "sass-loader",
                        "options": {
                            "sourceMap": true,
                            "precision": 8,
                            "includePaths": [
                                "C:\\workspace\\xxxxxx
                            ]
                        }
                    }
                ]
            },
            {
                "include": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.less$/,
                "use": [
                    "style-loader",
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "less-loader",
                        "options": {
                            "sourceMap": true,
                            "paths": [
                                "C:\\workspace\\xxxxxx
                            ]
                        }
                    }
                ]
            },
            {
                "include": [
                    path.join(process.cwd(), "src\\main\\ui\\scss\\styles.scss")
                ],
                "test": /\.styl$/,
                "use": [
                    "style-loader",
                    {
                        "loader": "raw-loader"
                    },
                    {
                        "loader": "postcss-loader",
                        "options": {
                            "ident": "embedded",
                            "plugins": postcssPlugins,
                            "sourceMap": true
                        }
                    },
                    {
                        "loader": "stylus-loader",
                        "options": {
                            "sourceMap": true,
                            "paths": [
                                "C:\\workspace\\xxxxx\\xxxxxx"
                            ]
                        }
                    }
                ]
            },
            {
                "test": /\.ts$/,
                "loader": "@ngtools/webpack"
            }
        ]
    },
    "plugins": [
        new NoEmitOnErrorsPlugin(),
        new ScriptsWebpackPlugin({
            "name": "scripts",
            "sourceMap": true,
            //"window":'this',
            "filename": "scripts.bundle.js",
            "scripts": [
                //  lots of library referenced here      ],
                "basePath": "C:\\workspace\\xxxx\\xxxx"
    }),
        new CopyWebpackPlugin([
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "lib\\**\\*",
                    "dot": true
                }
            },
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "styles",
                    "dot": true
                }
            },
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "images\\**\\*",
                    "dot": true
                }
            },
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "fonts\\**\\*",
                    "dot": true
                }
            },
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "favicon.ico",
                    "dot": true
                }
            },
            {
                "context": "src\\main\\ui",
                "to": "",
                "from": {
                    "glob": "WEB-INF\\**\\*",
                    "dot": true
                }
            }
        ], {
                "ignore": [
                    ".gitkeep",
                    "**/.DS_Store",
                    "**/Thumbs.db"
                ],
                "debug": "warning"
            }),
        new ProgressPlugin(),
        new NamedLazyChunksWebpackPlugin(),
        new HtmlWebpackPlugin({
            "template": "./src\\main\\ui\\index.html",
            "filename": "./index.html",
            "hash": false,
            "inject": true,
            "compile": true,
            "favicon": false,
            "minify": false,
            "cache": true,
            "showErrors": true,
            "chunks": "all",
            "excludeChunks": [
                "webworker"
            ],
            "title": "Webpack App",
            "xhtml": true,
            "chunksSortMode": function sort(left, right) {
                let leftIndex = entryPoints.indexOf(left.names[0]);
                let rightIndex = entryPoints.indexOf(right.names[0]);
                if (leftIndex > rightIndex) {
                    return 1;
                }
                else if (leftIndex < rightIndex) {
                    return -1;
                }
                else {
                    return 0;
                }
            }
        }),
        new BaseHrefWebpackPlugin({}),
        new CommonsChunkPlugin({
            "name": [
                "inline"
            ],
            "minChunks": null,
            "chunks": [
                "main",
                "polyfills",
                "styles"
            ]
        }),
        new CommonsChunkPlugin({
            "name": [
                "vendor"
            ],
            "minChunks": (module) => {
                return module.resource
                    && (module.resource.startsWith(nodeModules)
                        || module.resource.startsWith(genDirNodeModules)
                        || module.resource.startsWith(realNodeModules));
            },
            "chunks": [
                "main"
            ]
        }),
        new SourceMapDevToolPlugin({
            "filename": "[file].map[query]",
            "moduleFilenameTemplate": "[resource-path]",
            "fallbackModuleFilenameTemplate": "[resource-path]?[hash]",
            "sourceRoot": "webpack:///"
        }),
        new CommonsChunkPlugin({
            "name": [
                "main"
            ],
            "minChunks": 2,
            "async": "common"
        }),
        new NamedModulesPlugin({}),
        new AngularCompilerPlugin({
            "mainPath": "app2\\main.ts",
            "entryModule": "app2\\app.module#AppModule",
            "platform": 0,
            "hostReplacementPaths": {
                "environments\\environment.ts": "environments\\environment.ts"
            },
            "sourceMap": true,
            "tsConfigPath": "src\\main\\ui\\tsconfig.app.json",
            "skipxxxxxGeneration": true,
            "compilerOptions": {}
        })
    ],
    "node": {
        "fs": "empty",
        "global": true,
        "crypto": "empty",
        "tls": "empty",
        "net": "empty",
        "process": true,
        //"module": false,
        "clearImmediate": false,
        "setImmediate": false
    },
    "devServer": {
        "historyApiFallback": true,
        hot: false,
        // "globalObject": 'this',
        //    contentBase: __dirname + '/src',
        //   inline: true,
        //  host: '0.0.0.0',
        //   port: 4200, 
        //"host":'0.0.0.0',
        //"inline": true,
        // https: true,
        "port": 4200,
        // "contentBase": __dirname + '/xxxxx/',
        "proxy": {
            "/xxxxx/*": {
                "target": "https://xxxxxxxxx:20000/",
                "secure": false,
                "logLevel": "debug",
                "changeOrigin": true
            },
            "/xxxxxxxxxx-services/*": {
                "target": "https://xxxxxxxxxxx:20000/",
                "secure": false,
                "logLevel": "debug",
                "changeOrigin": true
            }
        }
    }
};

0 个答案:

没有答案