Kleioz
Kleioz

Reputation: 294

Use environment variable in Typescript with ParcelJS

Migrating a react app built with ParcelJS to Typescript/React, I encounter some environment variables issues. Actually, the issue seems to only impact the error output since the environment variables (URL, used in a <a> tag) works properly on the webpage.

Here is the terminal output:

/Users/---/Projects/---/---/src/cart/index.tsx(xxx,xxx)
Cannot find name 'process'.
126 |       method: "post",
127 |       url: `${process.env.URL}/checkout`,
    |               ^^^^^^^
128 |       data: cart,

I tried several approaches, as import * as process from "process" which didn't fix the issue:

Could not find a declaration file for module 'process'.
'./node_modules/process/index.js' implicitly has an 'any' type.
Try `npm install @types/process` if it exists or add a new 
declaration (.d.ts)     file containing `declare module 'process';`
  > 6 | import * as process from "process";
  |                          ^^^^^^^^^

Nevertheless if I try to output the variable that works :

const ENV = process.env.MIDDLEWARE_URL;
console.log('ENV', ENV);

Browser output:

ENV http://localhost:3000

Finally, I can't figure out if this is a Parcel issue or a TSConfig issue. Any ideas?

Upvotes: 2

Views: 2325

Answers (3)

Mats Faugli
Mats Faugli

Reputation: 169

Installing the correct type definitions as a dev dependency solves the problem: npm install @types/parcel-bundler --save-dev

Upvotes: 0

sidonaldson
sidonaldson

Reputation: 25284

To add to a comment answer left by @Kleioz because I still had to google what was happening...

The solution was to add typeRoots to the TypeScript config. This essentially tells the compiler where the node_module declarations are. You can also pass through a folder for custom declarations if required.

{
  "compilerOptions": {
    ...
    "typeRoots": ["./node_modules/@types", "./typings"]
    ...
  }
}

./typings is your folder for custom declarations.

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222409

In Node.js TypeScript development, @types/node package is supposed to be used for Node-specific declarations including process. It isn't suitable for browser because it likely has nothing in common with Node.js environment except process global.

process built-in module import is redundant in Node.js and certainly shouldn't be used in browser, because there's no such module (even though there is shim module, it isn't needed for process.env).

If process was defined by a bundler (ParcelJS) in client-side script, type declaration should be provided for it in custom type file (e.g. typings/custom.d.ts):

declare const process: {
    env: {
        ENV: string;
        URL: string;
    }
}

Custom typings path should be specified in TypeScript configuration as well:

"typeRoots": ["./node_modules/@types", "./typings"]

Upvotes: 3

Related Questions