Search code examples
angulartypescriptwebpackwebpack-2

Can't provide environment variable from Webpack config to Angular 2


In my config for Webpack I have the following.

var config = require("./webfig");
config.module = config.module || [];
config.plugins.push(new webpack.DefinePlugin({ "Hazaa": "Shazoo" }));
module.exports = config;

However, in the TS file, when I try to access it using the line below, the transpiler complains that such a thing isn't available. I'm not entirely certain how to troubleshoot it and googlearching produced not much of value for this specific issue (as far I've recognized the diagnostics properly).

How do I access Hazaa in my TypeScript code?

Edit

Based on the comments, I've introduced the following changes.

config.plugins.push(new webpack.DefinePlugin({ "Hazaa": JSON.stringify("Shazoo") }));

A file called app.d.ts is created in the same directory as the pre-existing index.d.ts was. It contains only declare var Hazaa: string; and I'm referring to it from typings.json like this.

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.9.7+20161130133742",
    "app": "file:./typings/app.d.ts"
  }
}

I also referred to it from tsconfig.json section files as follows.

{
  "compilerOptions": {
    "baseUrl": "./source/application",
    "target": "es5",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "files": [
    "typings/index.d.ts",
    "typings/app.d.ts"
  ],
  "include": [ "source/**/*" ],
  "exclude": [ "node_modules" ]
}

Nothing helps - when I go console.log(Hazaa) in the constructor of my component, I get the compile time error saying that the name can't be found.


Solution

  • As TypeScript doesn't know about the webpack global variables (variables defined with DefinePlugin) which is injected into the code when you build the project hence it gives an error. You have to tell TypeScript that the Hazaa is a variable of type string which would be evaluated at build time.

    So declare the Hazaa with your .d.ts file.

    declare var Hazaa: string;