无法加载浏览器依赖项Webpack

时间:2018-10-02 01:54:29

标签: node.js angular typescript webpack polyfills

我正在尝试手动搭建Angular 6应用程序(即不使用CLI)。我一直做得很好,直到运行webpack时遇到以下错误:

ERROR in window is not defined

现在,由于在webpack上使用node来生成它的输出,因此我似乎错过了一些polyfill。我已经在Angular的网站上查看了示例,并将polyfills.ts文件添加到了我的应用程序中,但是仍然无法摆脱错误。

这是我的webpack.confg.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtPlugin = require('script-ext-html-webpack-plugin');
const { AngularCompilerPlugin } = require('@ngtools/webpack');

module.exports = function() {
    return {
        entry: {
            index: "./src/client/client.ts",
            polyfills: "./src/client/polyfills.ts"
        },
        output: {
            path: __dirname + "/client-dist",
            filename: "[name].client.js"
        },
        resolve: {
            extensions: ['.ts', '.js']
        },
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    loader: '@ngtools/webpack'
                },
                {
                    test: /\.html$/,
                    loader: 'html-loader',
                },
                {
                    test: /\.css$/,
                    loader: ["style-loader", "css-loader"]
                }
            ]
        },
        plugins: [ 
            new HtmlWebpackPlugin({
                template: __dirname + '/src/client/index.html',
                output: __dirname + '/client-dist',
                inject: 'head'
            }),
            new ScriptExtPlugin({
                defaultAttribute: 'defer'
            }),
            new AngularCompilerPlugin({
               tsConfigPath: './tsconfig.json',
               entryModule: './src/client/app/app.module#AppModule'
            })
        ]
    }
}

我的polyfills.ts文件:

import 'core-js/es6';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';

还有我的client.ts文件(我的应用程序的入口):

import './polyfills'

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

platformBrowserDynamic().bootstrapModule(AppModule);

我确定我只是在做一些愚蠢的事情,但是任何帮助都将不胜感激。谢谢!

编辑1:

阅读@SureshKumarAriya发表的文章后,我尝试在webpack.config中更改以下内容:

new AngularCompilerPlugin({
    tsConfigPath: './tsconfig.json',
    entryModule: './src/client/app/app.module#AppModule',
    skipCodeGeneration: true // This is new
})

我收到另一个错误:ERROR in Resolution of relative paths requires a containing file.

我猜这意味着它无法解析我在client.ts中引用的打字稿文件之一?我不确定这是否使我更接近但仍然很有趣。

一如既往地感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

似乎您的依赖项仍依赖于window对象。

进行验证

typeof window !== 'undefined' 

请参阅以下link

答案 1 :(得分:0)

内部输出配置。请添加globalObject:“此”。

output: {
  // ...
  globalObject: "this"
}

https://github.com/markdalgleish/static-site-generator-webpack-plugin/issues/130