Michael Michael - 1 month ago 13
Javascript Question

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
. So here is the approach I am trying to take:

webpack.js Define part

new webpack.DefinePlugin({
environment: JSON.stringify('DEVELOPMENT'),
}),


globals.ts

declare const environment: String;
console.log(environment);
export { environment };
console.log(environment);


environmentService.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);
inside
environmentService.ts
is giving me
undefined
when I am expecting
DEVELOPMENT
and I am not sure why?

It appears it only
exports
the variable and not the value?

If someone can explain what I am doing wrong and why its getting
undefined
i would appreciate it.

Edit 1

I think I see what
DefinePlugin
is doing. Its not setting
environment
to
DEVELOPMENT
but rather replacing lines
console.log(environment);
with
console.log('DEVELOPMENT');
and when it
exports
environment
its undefined.

Answer Source

DefinePlugin inlines code parts, thats why you need all those JSON.stringify('DEVELOPMENT') not just 'DEVELOPMENT'. It replaces global identifiers it knows with the given code parts as is. If you define environment: '"PROD" + "DUCTION"'

Then

if(environment === 'PRODUCTION') {

}

Becomes

if("PROD" + "DUCTION" === 'PRODUCTION') {

}

Something like this should work in ts2

const env: String = environment;
export { env as environment };