Reputation: 1501
Is there a project with TypeScript definitions for "process" variable to use process.env.NODE_ENV? Couldn't find anywhere.
Upvotes: 38
Views: 54064
Reputation: 2918
If your are using create-react-app your-app-test --template typescript
then already exist a file to set your environment variables.
file name: react-app-env.d.ts
located at src
folder.
then you can set in that file your custom env
variables with this template:
/// <reference types="react-scripts" />
declare global {
namespace NodeJS {
interface ProcessEnv {
GITHUB_AUTH_TOKEN: string;
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
}
}
}
// If this file has no import/export statements (i.e. is a script)
// convert it into a module by adding an empty export statement.
export {}
Upvotes: 2
Reputation: 61
declare namespace NodeJS {
interface ProcessEnv {
[key: string]: string | undefined
NODE_ENV?: 'development' | 'production' | 'test'
}
}
put the code above in your file global.d.ts
Upvotes: 4
Reputation: 14435
If you get this error in VSCode, maybe you just need to restart it.
Upvotes: 0
Reputation: 4285
Use the types from Definitely Typed via npm/yarn:
# Install the latest
npm install --save-dev @types/node
# or
yarn add @types/node --dev
# To install the right types for your version of node (e.g. 12 here)
npm install --save-dev @types/node@^12
yarn add @types/node@^12 --dev
With your types available, the object process.env
should be available in your code.
process.env
You can use declaration merging to add new values to process.env
. Create a new d.ts
file in your project, then add:
declare global {
namespace NodeJS {
interface ProcessEnv {
NODE_ENV?: string
}
}
}
This will let you write process.env.NODE_ENV
. I'd recommend keeping the ? in unless you have validation that it's set somewhere in the library.
Upvotes: 7
Reputation: 22352
The definitions for the 'process' variable can be found in default node.js d.ts from definitely typed and added in your typings.json like this:
"node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts"
I do not think there are any definitions for the particular NODE_ENV variable. As it is just a convention (widely used by express link) and node.js itself does not care about that specific environment variable.
Upvotes: 14
Reputation: 1551
just add before use process.env.NODE_ENV
declare var process : {
env: {
NODE_ENV: string
}
}
Upvotes: 8
Reputation: 12683
Update for Node 8:
Now env
is declared as ProcessEnv
in DefinitelyTyped.
env: ProcessEnv;
export interface ProcessEnv {
[key: string]: string | undefined;
}
TypeScript 2 supports npm package type definitions for node. It currently uses the DefinitivelyTyped node.d.ts.
npm install --save-dev @types/node
Pre Node 8 version:
process env
is declared as any
in DefinitelyTyped node.d.ts.
env: any;
Upvotes: 46