Angular Dependency Injection does not work with Webpack

Viewed 362

I've got an issue that Angular Dependency Injection does not work when I build the project with Webpack.

I use Angular 13 and Webpack 5, I use the @Injectable decorator to mark a service class and pass it to a component constructor:

@Injectable({  providedIn: 'root'})
export class DITestService {
  
  constructor() { }
  
  getTitle(){
    return "DI testing";
  }
}

@Component({
  selector: 'app-root',
  template: '<div>Title: {{ title }}</div>'
})
export class AppComponent {  
  public title: string = this.diTestService.getTitle();  
  
  constructor(private diTestService: DITestService)  
  {  }
}

When I run the project I get the following error:

Error: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.

Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors.

When I run the same project via Angular CLI, without Webpack, it works fine.

When I use the @Inject decorator in the component constructor and build the project with Webpack it also works fine.

constructor(@Inject(DITestService) private diTestService: DITestService)

Is it possible to configure Webpack to use dependency injection without the @Inject decorator?

The details of my test project are the following:

app.component.ts

import { Component } from '@angular/core';
import { DITestService } from './ditest-service.service';

@Component({
  selector: 'app-root',
  template: '<div>Title: {{ title }}</div>'
})
export class AppComponent {  
  public title: string = this.diTestService.getTitle();  
  
  constructor(private diTestService: DITestService)  
  {  }
}

ditest-service.service.ts

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

@Injectable({  providedIn: 'root'})
export class DITestService {
  
  constructor() { }
  
  getTitle(){
    return "DI testing";
  }
}

app.module.ts

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

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

import { DITestService } from './ditest-service.service';

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

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularTest1</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <app-root></app-root>
</body>
</html>

main.ts

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

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

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

polyfills.ts

import 'zone.js'; 

package.json

{
  "name": "angular-test1",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "webpack_serve": "webpack serve --mode development",
    "webpack_build": "webpack --mode production"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.0.0",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",    
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.4",
    "@angular/cli": "~13.0.4",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "angular2-template-loader": "^0.6.2",
    "html-webpack-plugin": "^5.5.0",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "ts-loader": "^9.2.6",
    "typescript": "~4.4.3",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.1"
  }
}

tsconfig.json

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist",
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": false,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'app': './src/main.ts'
    },
    output:{
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        filename: '[name].[fullhash].js'
    },
    devServer: {
        historyApiFallback: true,
        port: 40042,
        open: false
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module:{
        rules:[
            {
                test: /\.ts$/,
                use: [
                    'ts-loader',
                    'angular2-template-loader'
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
}
1 Answers

As it was suggested in comments:

It is possible with AngularCompilerPlugin (it transforms angular templates and some transformations is also done on ts classes).

npmjs.com/package/@ngtools/webpack

Related