Angular + Webpack:初始化时为空角对象

时间:2016-04-30 20:24:20

标签: angularjs webpack

尝试使用webpack + angular 1.5.5 + ng-forward。 Webpack解析角度并逐个模块构建它。在角度初始化期间,我在以下函数中得到错误:

(function extendJQLite(proto) {
    ...
})(angular.element.prototype);

出现错误是因为angular对象为空({})。为什么会这样?如何修复(除了将角度移动到externals)?

我的Webpack配置:

{
    debug: true,
    cache: true,

    verbose: true,
    displayErrorDetails: true,
    context: './src',
    stats: {
        colors: true,
        reasons: true
    },
    entry: "./index.ts",
    output: {
        path: './build',
        filename: "build.js"
    },
    resolve: {
        extensions: ['', '.js', '.ts']
    },
    module: {
        loaders: [
            { test: /\.ts/, exclude: /node_modules/, loader: 'babel-loader!ts-loader' }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            __metadata: 'typescript-metadata',
            __decorate: 'typescript-decorate',
            __awaiter: 'typescript-awaiter',
            __param: 'typescript-param',
            angular: 'angular'
        })
    ]
}

2 个答案:

答案 0 :(得分:0)

好的,我用两种方式解决了它:

1)在imports-loader之后的主要加载器部分中使用babel-loader

loaders: [
    { test: /\.ts/, exclude: /node_modules/, loader: 'import?angular!babel-loader!ts-loader' }
]

它有效,但还有一些其他麻烦迫使我停止使用这种方式。所以还有另一种方式:

2)我刚创建了一个文件vendor.js,其中需要所有依赖项。据我所知,这是使用webpack库的正确方法。

答案 1 :(得分:0)

有完全相同的问题并找到了解决方案。这里的问题是,如果没有垫片,角度1与webpack不能很好地协同工作(参见https://github.com/webpack/webpack/issues/2049)。试试这个webpack loader配置:

module: {
    loaders: [
        /*
         * Necessary to be able to use angular 1 with webpack as explained in https://github.com/webpack/webpack/issues/2049
         */
        {
            test: require.resolve('angular'),
            loader: 'exports?window.angular'
        },
    ]
},
plugins: [
    new webpack.ProvidePlugin({
        'angular': 'angular',
    }),
],