繁体   English   中英

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

[英]Angular Component Service Injection Does Not Work With Webpack

问题

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

Compiler.js:485未捕获的错误:无法解析AppComponent的所有参数(?)。

./src/app/main.js

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

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

platformBrowserDynamic().bootstrapModule(AppModule);

./src/app/test.service.ts

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

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

./src/app/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/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上获得此问题的示例项目的源。 然后运行:

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

core-js导入您的app.module.ts ,这将添加app.module.ts

import 'core-js';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM