[英]global variables are undefined in typescript coming from webpack
In typescript 2.4.0
I am trying to create global/environment variables using DefinePlugin
using webpack
.在
typescript 2.4.0
我尝试使用DefinePlugin
使用webpack
创建全局/环境变量。 So here is the approach I am trying to take:所以这是我试图采取的方法:
webpack.js Define part webpack.js 定义部分
new webpack.DefinePlugin({
environment: JSON.stringify('DEVELOPMENT'),
}),
globals.ts globals.ts
declare const environment: String;
console.log(environment);
export { environment };
console.log(environment);
environmentService.ts环境服务.ts
import { IEnvironment } from 'environment';
import { environment } from '../globals';
console.log(environment);
export default class EnvironmentService implements IEnvironment {
environmentName: String = environment;
get isDevelopment(): boolean {
return this.environmentName === 'DEVELOPMENT';
}
get isProduction(): boolean {
return this.environmentName === 'PRODUCTION';
}
}
In the console log I get:在控制台日志中,我得到:
DEVELOPMENT
DEVELOPMENT
undefined
So console.log(environment);
所以
console.log(environment);
inside environmentService.ts
is giving me undefined
when I am expecting DEVELOPMENT
and I am not sure why?当我期待
DEVELOPMENT
时,内部environmentService.ts
给了我undefined
,我不知道为什么?
It appears it only exports
the variable and not the value?它似乎只
exports
变量而不是值?
If someone can explain what I am doing wrong and why its getting undefined
i would appreciate it.如果有人可以解释我做错了什么以及为什么它变得
undefined
我将不胜感激。
Edit 1编辑 1
I think I see what DefinePlugin
is doing.我想我看到了
DefinePlugin
在做什么。 Its not setting environment
to DEVELOPMENT
but rather replacing lines console.log(environment);
它不是将
environment
设置为DEVELOPMENT
而是替换行console.log(environment);
with console.log('DEVELOPMENT');
与
console.log('DEVELOPMENT');
and when it exports
environment
its undefined.当它
exports
environment
时,它的未定义。
You can create a @types
folder and put a declaration file global.d.ts
in it, with just below content.您可以创建一个
@types
文件夹并在其中放置一个声明文件global.d.ts
,其内容就在下面。
declare const environment: String;
TypeScript includes all @types
packages by default during compilation: https://www.typescriptlang.org/tsconfig#types TypeScript 在编译过程中默认包含所有
@types
包: https : @types
DefinePlugin inlines code parts, thats why you need all those JSON.stringify('DEVELOPMENT')
not just 'DEVELOPMENT'
. DefinePlugin 内联代码部分,这就是为什么你需要所有那些
JSON.stringify('DEVELOPMENT')
而不仅仅是'DEVELOPMENT'
。 It replaces global identifiers it knows with the given code parts as is.它按原样用给定的代码部分替换它知道的全局标识符。 If you define
environment: '"PROD" + "DUCTION"'
如果您定义
environment: '"PROD" + "DUCTION"'
Then然后
if(environment === 'PRODUCTION') {
}
Becomes成为
if("PROD" + "DUCTION" === 'PRODUCTION') {
}
Something like this should work in ts2这样的东西应该在 ts2 中工作
const env: String = environment;
export { env as environment };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.