乐闻世界logo
搜索文章和话题

How to set environment variables from within package.json ?

1个答案

1

Directly setting environment variables in package.json is not common, as this file is primarily intended for defining project dependencies, scripts, and configuration information. However, you can define script commands within the scripts section of package.json to set environment variables during execution.

For example, on Unix-like systems (such as Linux or macOS), you can use the export command to set environment variables and then execute other commands. On Windows, you may need to use the set command or a cross-platform solution like cross-env.

Here is an example of how to set environment variables in the scripts section:

json
{ "name": "your-package", "version": "1.0.0", "scripts": { "start": "export NODE_ENV=production && node app.js", "start:windows": "set NODE_ENV=production && node app.js" } }

In the above example, we set the NODE_ENV environment variable to production in the start script and then execute node app.js.

Using cross-env, you can write a cross-platform script command:

json
{ "name": "your-package", "version": "1.0.0", "scripts": { "start": "cross-env NODE_ENV=production node app.js" }, "devDependencies": { "cross-env": "^7.0.3" } }

In this example, regardless of the operating system, the start script will set the NODE_ENV environment variable to production and then run node app.js. Note that you need to install cross-env as a dev dependency (using the command npm install --save-dev cross-env).

This approach is highly flexible, allowing you to run different commands in various environments (development, testing, production, etc.). Remember that the environment variables set here only exist during script execution and do not affect other shell processes after the script completes.

2024年6月29日 12:07 回复

你的答案