Search code examples
ts-node

Why ts-node throws the ReferenceError on undefined variables?


Normally, the reference error is being thrown when we are invoking some property from variable with undefined value. For example foo.substring(1); will cause the ReferenceError if foo has not been defined.

But why ts-node throws the same error because of below one?

console.log(__IS_LOCAL_DEVELOPMENT_BUILDING_MODE__);

The error message is:

console.log(__IS_LOCAL_DEVELOPMENT_BUILDING_MODE__);
            ^
ReferenceError: __IS_LOCAL_DEVELOPMENT_BUILDING_MODE__ is not defined

O'K __IS_LOCAL_DEVELOPMENT_BUILDING_MODE__ has not been defined. So what? Why the ts-node not output the undefined?


Solution

  • Cannot read property of undefined and [foo] is not defined are different. Using undeclared variables gets you a has not been defined.

    A reference to an undeclared variable should not give you back undefined, because undefined is for variables that have been declared but not given a value (or explicitly given the value undefined).

    Are you declaring __IS_LOCAL_DEVELOPMENT_BUILDING_MODE__ anywhere? Because Node won't just pick that up from your environment, if that's what you're expecting (that's my assumption based on your variable name). You could do something like const isDev = !!process.env.__IS_LOCAL_DEVELOPMENT_BUILDING__MODE

    And FWIW, this is just a JS thing, not a TypeScript thing; trying to access undeclared variables will always result in an error in strict mode (which is always-on in modules).

    Here's an example of code that would produce each of those two different errors:

    const exampleOfPropertyError = (foo) => {
      console.log(foo.bar)
    }
    exampleOfPropertyError()
    
    const exampleOfUndeclaredError = console.log(ljksdflkjsflkjsdf)
    

    And an example of how to work with env vars:

    const isDevelopmentMode = !!process.env.__IS_LOCAL_DEVELOPMENT_BUILDING_MODE__
    
    console.log(isDevelopmentMode)