How to declare in initialize global variable in TS-Node?

Viewed 1857

With Webpack:

const WebpackConfig = {
  // ...
  plugins: [
    new Webpack.DefinePlugin({
      __IS_DEVELOPMENT_BUILDING_MODE__: isDevelopmentBuildingMode,
      __IS_TESTING_BUILDING_MODE__: isTestingBuildingMode,
      __IS_PRODUCTION_BUILDING_MODE__: !isDevelopmentBuildingMode && !isTestingBuildingMode
    })
  ]
}

Now I'm going to use TS-Node instead of Webpack. TS-Node does not see these constants:

ErrorsReportingService.ts:35:9 - error TS2304: Cannot find name '__IS_DEVELOPMENT_BUILDING_MODE__'.

How to initialize these globals for TS-Node?

Off course, typings for these constants are being provided:

declare const __IS_DEVELOPMENT_BUILDING_MODE__: boolean;
declare const __IS_TESTING_BUILDING_MODE__: boolean;
declare const __IS_PRODUCTION_BUILDING_MODE__: boolean;

Please note that I need both Webpack and TSNode.

Solution on conceptual level

  1. Create file and initialize global variables (like globalThis.__IS_DEVELOPMENT_BUILDING_MODE__ = false ?)
  2. Tell TSNode to execute this file first.

Now the question is TSNode allows such things or not.

Update

My TypeScript lost the declared globals after I placed them inside declare global {}:

typings.d.ts

declare global {
  let __IS_DEVELOPMENT_BUILDING_MODE__: boolean;
  let __IS_TESTING_BUILDING_MODE__: boolean;
  let __IS_PRODUCTION_BUILDING_MODE__: boolean;
}

Now compiler does not see them:

TS2304: Cannot find name '__IS_DEVELOPMENT_BUILDING_MODE__'.

enter image description here

2 Answers

Step 1: Make TypeScript aware of your globals

The canonical way to define globals that exist both in Node.js and on the server is to use the var keyword.

declare global {
  var __IS_DEVELOPMENT_BUILDING_MODE__: boolean;
  var __IS_TESTING_BUILDING_MODE__: boolean;
  var __IS_PRODUCTION_BUILDING_MORE__: boolean;
}

This makes them accessible via globalThis and by referencing them directly.

globalThis.__IS_DEVELOPMENT_BUILDING_MODE__;
__IS_DEVELOPMENT_BUILDING_MODE__;

Step 2: Define them on the client

That's what Webpack.DefinePlugin is already doing for you.

Step 3: Define them on the server

Find the entry point of your Node application and define the variable there.

var __IS_DEVELOPMENT_BUILDING_MODE__ = true;

A common practice is to use environment variables.

var __IS_DEVELOPMENT_BUILDING_MODE__ = process.env.NODE_ENV === 'development;

one way here is you can use a class here like.

export class Config{
/*add field like this*/
 __IS_DEVELOPMENT_BUILDING_MODE__: boolean;
 __IS_TESTING_BUILDING_MODE__: boolean;
 const __IS_PRODUCTION_BUILDING_MODE__: boolean;
}

and then use in your code using import like.

import {Config} from 'your file location'
Config.your_variable_name
Related