角度组件服务注入不适用于Webpack

时间:2018-01-23 03:24:59

标签: javascript angular webpack

问题

我遇到的问题是,如果我在注入服务时在组件的构造函数中使用@Inject装饰器(即@Inject(TestService)),Angular的DI似乎才有效。每当我使用标准的Angular CLI测试项目时,这似乎工作正常(不使用@Inject),但是当我使用webpack手动创建没有Angular CLI的相同项目时(如下所示),我总是得到:

  

compiler.js:485 Uncaught Error:无法解析AppComponent的所有参数:(?)。

代码

./ SRC /应用/ main.js

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

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

platformBrowserDynamic().bootstrapModule(AppModule);

./ SRC /应用/ test.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class TestService {
    write() {
        console.log('SOMETHING');
    }
}

./ SRC /应用/ app.module.js

import 'zone.js/dist/zone';

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

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

import { TestService } from './test.service';

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

./ SRC /应用/ app.component.ts

import { Component, Inject } from '@angular/core';
import { TestService } from './test.service';

@Component({
    selector: 'app-root',
    styles: [],
    template: 'Hello',
})
export class AppComponent {
    // Works if you uncomment the @Inject decorator below
    constructor(/*@Inject(TestService)*/ test: TestService) {
        test.write();
    }
}

./ SRC / index.html中

<!DOCTYPE html>
<html lang="en">
<head>
    <title>test</title>
</head>
<body>
    <app-root></app-root>
</body>
</html>

./ webpack.common.js

const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const isVendorModule = (module) => {
    if (!module.context) {
        return false;
    }

    const nodeModule = module.context.indexOf('node_modules') !== -1;
    return nodeModule;
};

module.exports = {
    devServer: {
        contentBase: './src',
        historyApiFallback: true,
        quiet: true,
        stats: 'minimal'
    },
    entry: {
        'app/main': './src/app/main.ts'
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader'
            },
            {
                test: /\.(html)$/,
                loader: 'html-loader'
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin([
            path.resolve(__dirname, 'build/*')
        ]),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'app/vendor',
            chunks: ['app/main'],
            minChunks: isVendorModule
        }),
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html',
            chunks: ['app/vendor', 'app/main']
        })
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'build')
    }
};

./ tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    "noImplicitAny": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "es6",
    "target": "ES2016",
    "allowJs": true,
    "sourceMap": true,
    "types": [],
    "baseUrl": ".",
    "paths": {}
  },
  "exclude": [
    "node_modules",
    "dist",
    "build"
  ]
}

可重复样品

您可以在GitHub here上获取此问题示例项目的来源。然后运行:

  • npm install
  • npm run server
  • 访问localhost:8080

1 个答案:

答案 0 :(得分:2)

core-js内导入app.module.ts,这会添加polyfill。

import 'core-js';