簡體   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