简体   繁体   中英

Unable to change environmental variables in node.js in Visual Studio Code

I'm new here and I'm new with this programming language, so maybe my question is something very obvious.

I am trying to set an environmental variable in Node.js in Visual Studio Code (for example NODE_ENV to production). I've tried setting it using an .env file and using the dotenv package. This does not seem to work, and when I try to print the variable to the console it prints 'undefined'. This is the part that I have included in the .env file:

NODE_ENV = production 

This is a part of the js file that I try to run:

 const path = require('path') require('dotenv').config() console.log(process.env.NODE_ENV)

When I run this 'undefined' gets printed to the console. I also tried passing the place of the file as an argument with the config for dotenv, like this . That did not work. I even tried to set te environmental variables directly via launch.json like this:

 "version": "0.2.0", "configurations": [ { "type": "pwa-node", "request": "launch", "name": "Launch Program", "skipFiles": [ "<node_internals>/**" ], "program": "${file}", "env": { "NODE_ENV" : "production", } } ] }

That also did not work.

Why is this? Why isn't Visual Studio Code able to change the environmental variables? Thanks in advance.

According to the docs of dotenv there should be no space between the variable name and its value.

The syntax is: VARNAME=VALUE

So your .env file should be

NODE_ENV=production

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