Home > OS >  Angular - Webpack definePlugin variable is not defined
Angular - Webpack definePlugin variable is not defined

Time:09-30

I'm trying to inject variables into my code through Webpack's definePlugin.

And after reading numerous posts nothing seems to work. I have a feeling I'm missing something...

My webpack config is -

webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      $TEST: JSON.stringify(true),
      $ENV: {
        ENVIRONMENT: JSON.stringify(process.env.ENVIRONMENT) || 'localhost',
        API_URL: JSON.stringify(process.env.API_URL)
      }
    })
  ]
};

I created typing.d.ts file to declare variables :

declare let $ENV: Env;
declare let $TEST: boolean;

interface Env {
  ENVIRONMENT: string;
  API_URL: string;
}

then i'm trying to log variables in my main.ts file :

console.log('Test '   $TEST);
console.log('Environment :', $ENV.ENVIRONMENT);

But I receive the next error when launch 'ng serve' command

enter image description here

I'm using :

  • webpack : 5.54.0
  • "@angular-builders/custom-webpack": "^12.1.2",
  • "@angular-devkit/build-angular": "~12.2.7",
  • "@angular/cli": "~12.2.7",

Does anyone has any idea to fix it please ?

CodePudding user response:

This will only work for ng build, for ng serve we will need to add another custom angular-builder to our angular.json:

"serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            },
            "ci": {
              "progress": false
            }
          }
        },

Important, some other posts mentions to use @angular-builders/dev-server:generic builder.

But this one is deprecated (see angular-builders migration)

@angular-builders/dev-server:generic has been deprecated. Use @angular-builders/custom-webpack:dev-server instead.

  • Related