简体   繁体   中英

Typescript Reference error is not defined, webpack angular2

This is not a general not defined error, I've been trying to debug it for the past two hours.
I am defining a value in webpack plugins (for a global variable) for API endpoint and trying to access it in the application gives a weird error. So here is the plugins structure in webpack.dev.js (which merges into webpack.config.js).

new DefinePlugin({
    'ENV': JSON.stringify(METADATA.ENV),
    'HMR': METADATA.HMR,
    // ... some other lines
    'API_PARENT': "DEV_PARENT_TEST" // this is the line in question
})

in custom-typings.d.ts I have declared it to avoid ts erros

declare var API_PARENT: string;

Now in one of my app components when I try console.log(API_PARENT) I get the mysterious error bellow

EXCEPTION: Uncaught (in promise): ReferenceError: DEV_PARENT_TEST is not defined
ReferenceError: DEV_PARENT_TEST is not defined

The stack trace leads to that log line. The part I don't get is that why this is throwing up in the first place. the DEV_PARENT_TEST is a value not even a key why is there a reference error on it!

I am answering this just in case someone else faced this error. It wasted 3 hours of my time until I solve it. The clue was in the first line JSON.stringify .

You must do that for all your string values. So the only change is in webpack.dev.js which should be

'API_PARENT': JSON.stringify("DEV_PARENT_TEST")

That that solves it all. Most likely this was a webpack question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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