简体   繁体   English

无法提供从Webpack配置到Angular 2的环境变量

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

In my config for Webpack I have the following. 在我的Webpack配置中,我有以下内容。

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. 但是,在TS文件中,当我尝试使用下面的行访问它时,编译器抱怨说这样的事情不可用。 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). 我不确定如何解决该问题,并且googlearching对于该特定问题没有多大价值(到目前为止,我已经正确识别了诊断程序)。

How do I access Hazaa in my TypeScript code? 如何在TypeScript代码中访问Hazaa

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. 在与先前存在的index.d.ts相同的目录中创建了一个名为app.d.ts的文件。 It contains only declare var Hazaa: string; 它仅包含declare var Hazaa: string; and I'm referring to it from typings.json like this. 我是从这样的types.json引用它的。

{
  "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. 我还从tsconfig.json文件中引用了它,如下所示。

{
  "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. 没有任何帮助-当我在组件的构造函数中进入console.log(Hazaa)时,出现编译时错误,提示找不到该名称。

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. 由于TypeScript不了解webpack全局变量(使用DefinePlugin定义的变量),因此在构建项目时会将其注入代码中,因此会产生错误。 You have to tell TypeScript that the Hazaa is a variable of type string which would be evaluated at build time. 您必须告诉TypeScript Hazaa是字符串类型的变量,将在构建时对其进行评估。

So declare the Hazaa with your .d.ts file. 所以申报Hazaa你.d.ts文件。

declare var Hazaa: string;

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

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