Home>Article>Backend Development> A better way to manage front-end environment variables

A better way to manage front-end environment variables

小云云
小云云 Original
2017-12-05 16:46:55 1930browse

This article mainly analyzes the problems encountered when using environment variables to manage front-end projects, and introduces common tools to provide solutions.

How to use environment variables

When building a front-end project based on webpack (or any Node-based Projects (this article takes the webpack project as an example) generally need to provide two operating modes: development mode and production mode. The usual approach is to set the environment variableNODE_ENVtoproductionbefore executing the command. , such as executing theNODE_ENV=production webpackcommand, and then passingprocess.env.NODE_ENV === in the JavaScript code 'production'to determine whether it is production mode, otherwise it is development mode. By distinguishing between different modes, you can perform different operations, such as starting a development server and proxy forwarding APIs in development mode, or compressing and merging code in production mode. In order to better unify the front-end engineering commands, you can add the commands to start development mode and production mode to the scripts field of the package.json file respectively. In the future, you only need to executenpm startornpm run build. The need to perform differential operations in the project is well solved by defining environment variables. If you want to support member-defined environment variables, just use the value in the environment variable first in the program. For example, if the port number has been set to give priority to the value ofPORTin the environment variable, project members will executePORT=8080 when developing. npm startcommand can customize the port number to 8080.

Problems encountered when using environment variables

The above solutions can be applied to most scenarios, but they cannot solve the problem of setting environment variables. Cross-platform and persistence issues

Cross-platform

If there are members using the Windows operating system in the project, It will fail when executingnpm run build(i.e.NODE_ENV=production webpack) , because Windows commands do not support setting environment variables in this way. Although you can also manually executeset NODE_ENV=production webpackunder Windows based on the content of the build script, it destroys the original intention of unifying front-end engineering commands. For this reason, Introducing a library that solves the problem of setting environment variables across platforms. If using cross-env, just rewrite the build script in package.json tocross-env NODE_ENV=production webpackand it will work across platforms.

Persistence

As the scale of the project increases, the number of custom environment variables for the project may increase. many. For example, static resources need to use CDN after deployment, and the project production mode needs to provide an environment variable to support the publicPath field of custom webpack; for example, some members do not run the API server locally, but run it in a virtual machine. Or on another computer, the project development mode needs to provide two environment variables to support the custom API server address and port number... Some members may have to execute a long command like this every time they develop:PORT=8080 API_SERVER=192.168.100.100 API_PORT=9000 npm start, so you need a tool that can persist environment variables, such as dotenv or env-cmd. Taking env-cmd as an example, you only need to create a .env.local file (not included in version management) and write:

NODE_ENV=development
PORT=8080
API_SERVER=192.168.100.100
API_PORT=9000

Rewrite the start command (build command) in package.json Similar) isenv-cmd --fallback ./.env.local webpackto solve the problem of too many custom environment variables and tedious manual input each time. .

真正好用的环境变量管理工具

管理环境变量有很多工具,下面简单分析一下常用工具 dotenv、cross-env 和 env-cmd 的优势与不足:

  • dotenv 可以解决跨平台和持久化的问题,但使用场景有限,只适用 node 项目,且和项目代码强耦合,需要在 node 代码运行后手动执行触发

  • cross-env 支持在命令行自定义环境变量。问题也非常明显,不能解决大型项目中自定义环境变量的持久化问题

  • env-cmd 也可以解决跨平台和持久化的问题,支持定义默认环境变量,不足的是不支持在命令行中自定义环境变量

事实上 NPM 本身也提供了类似设置项目环境变量的功能。以上述自定义端口号的需求为例,也可以在项目目录下执行npm config set project-name:PORT 8080(project-name 为项目名称),执行npm start后在代码中可以通过process.env.npm_package_config_PORT获取到 8080。而且还可以将 package.json 中 config 字段设置为{"PORT": 8000},用于指定npm_package_config_PORT的默认值。使用 NPM 的 config 功能管理环境变量的最大优势是原生支持,放在 package.json config 字段中的默认环境变量也非常方便查看。遗憾是的,变量名前面都会有冗长的npm_package_config_;脚本必须从 package.json 的 scripts 字段中执行(即执行 npm run your_script_name);还有就是所有项目共用一份配置文件(.npmrc,默认在用户目录下),不方便手动编辑和查看。

因此一个好用的前端环境变量管理工具应该具备以下功能:

  • 支持命令行设置环境变量

  • 跨平台

  • 持久化,最好能够提供一个设置本地环境变量的命令行工具

  • 支持设置默认环境变量

  • 支持获取 NPM 提供的环境变量(npm_package_*npm_config_*

为此又诞生了一个环境变量管理工具:fuck-env,取义“恶搞环境变量”,支持以上所有功能。

fuck-env 安装和使用

npm install fuck-env

如有一个包含 package.json 和 main.js 两个文件的项目,文件代码如下:

package.json

{
"name": "fuck-env-demo",
"config": {
"PORT": 8000,
"APP_NAME": "$npm_package_name"
},
"scripts": {
"start": "fuck-env node main.js"
},
"dependencies": {
"fuck-env": "*"
}
}

main.js

console.log(process.env.PORT) // 8080
console.log(process.env.APP_NAME) // fuck-env-demo

执行fuck-env PORT=8080 npm start后,输出“8080”和“fuck-env-demo”,不论是在 Windows 还是 POSIX(macOS、Linux 等)系统中。

如果成员希望本地持久化自定义的端口号,可以新建一个 .env 文件(此文件须加入 .gitignore,不计入版本管理,格式为类 .ini 文件的简单键值对)。

.env

PORT=8080

以后只需执行npm start即可。此外 fuck-env 还提供了另一个命令行工具:fuck,用于快速设置本地环境变量。比如,如果成员又希望使用 9000 端口,可以在项目根目录下执行fuck set PORT 9000(需全局安装 fuck-env),此时项目目录下 .env 文件的内容即会变为“PORT=9000”,使用 fuck 命令在环境变量较多时非常方便。

When there are too many environment variables, all the config fields in package.json will also appear bloated. fuck-env supports unified management of default environment variables. Just move all environment variables under the config field to the default.env file (included in the version library).

For more examples, please refer here

fuck-env is committed to solving various problems encountered by users when managing environment variables. Currently, It is in the Beta stage and more user-friendly designs will be added in the future. If you have any ideas, welcome to give valuable suggestions to the project.


Original address: https://lon.im/post/use-envir...

This article mainly analyzes the problems encountered when using environment variables to manage front-end projects, and introduces common tools to provide solutions.

How to use environment variables

#When building a front-end project based on webpack (or any project based on Node, this article takes the webpack project as an example) , generally need to provide two operating modes: development mode and production mode. The usual approach is to set the environment variableNODE_ENVtoproductionbefore executing the command. , such as executing theNODE_ENV=production webpackcommand, and then passingprocess.env.NODE_ENV === in the JavaScript code 'production'to determine whether it is production mode, otherwise it is development mode. By distinguishing between different modes, you can perform different operations, such as starting a development server and proxy forwarding APIs in development mode, or compressing and merging code in production mode. In order to better unify the front-end engineering commands, you can add the commands to start development mode and production mode to the scripts field of the package.json file respectively. In the future, you only need to executenpm startornpm run build. The need to perform differential operations in the project is well solved by defining environment variables. If you want to support member-defined environment variables, just use the value in the environment variable first in the program. For example, if the port number has been set to give priority to the value ofPORTin the environment variable, project members will executePORT=8080 when developing. npm startcommand can customize the port number to 8080.

Problems encountered when using environment variables

The above solutions can be applied to most scenarios, but they cannot solve the problem of setting environment variables. Cross-platform and persistence issues

Cross-platform

If there are members using the Windows operating system in the project, It will fail when executingnpm run build(i.e.NODE_ENV=production webpack) , because Windows commands do not support setting environment variables in this way. Although you can also manually executeset NODE_ENV=production webpackunder Windows based on the content of the build script, it destroys the original intention of unifying front-end engineering commands. For this reason, Introducing a library that solves the problem of setting environment variables across platforms. If using cross-env, just rewrite the build script in package.json tocross-env NODE_ENV=production webpackand it will work across platforms.

Persistence

As the scale increases, the number of project custom environment variables may increase. For example, static resources need to use CDN after deployment, and the project production mode needs to provide an environment variable to support the publicPath field of custom webpack; for example, some members do not run the API server locally, but run it in a virtual machine. Or on another computer, the project development mode needs to provide two environment variables to support the custom API server address and port number... Some members may have to execute a long command like this every time they develop:PORT=8080 API_SERVER=192.168.100.100 API_PORT=9000 npm start, so you need a tool that can persist environment variables, such as dotenv or env-cmd. Taking env-cmd as an example, you only need to create a .env.local file (not included in version management) and write:

NODE_ENV=development
PORT=8080
API_SERVER=192.168.100.100
API_PORT=9000

Rewrite the start command (build command) in package.json Similar) isenv-cmd --fallback ./.env.local webpackto solve the problem of too many custom environment variables and tedious manual input each time. .

Really useful environment variable management tools

There are many tools for managing environment variables. Let’s briefly analyze the commonly used tools dotenv and cross-env. Advantages and disadvantages of env-cmd:

  • dotenv can solve cross-platform and persistence problems, but its usage scenarios are limited and is only applicable to node projects, and The project code is strongly coupled and needs to be triggered manually after the node code is run.

  • cross-env supports customizing environment variables on the command line. The problem is also very obvious. It cannot solve the persistence problem of custom environment variables in large projects.

  • env-cmd can also solve the problem of cross-platform and persistence. It supports defining default environment variables. The disadvantage is that it does not support customizing environment variables in the command line.

In fact, NPM itself also provides similar settings for project environment variables. Function. Taking the above requirement for custom port numbers as an example, you can also executenpm config set project-name:PORT 8080in the project directory (project-name is Project name), after executingnpm start, you can passprocess.env.npm_package_config_PORT## in the code# Obtained 8080. And you can also set the config field in package.json to{"PORT": 8000}to specifyDefault value for npm_package_config_PORT. The biggest advantage of using NPM's config function to manage environment variables is native support. The default environment variables placed in the package.json config field are also very convenient to view. Unfortunately, there will be a lengthynpm_package_config_in front of the variable name; the script must be executed from the scripts field of package.json (that is, execute npm run your_script_name); Also, all projects share a configuration file (.npmrc, in the user directory by default), which is inconvenient for manual editing and viewing.

Therefore, a useful front-end environment variable management tool should have the following functions:

  • Support command line setting environment Variables

  • Cross-platform

  • Persistence, it is best to provide a setting for the local environment Variable command line tool

  • Supports setting default environment variables

  • Supports obtaining NPM provided Environment variables (npm_package_*andnpm_config_*)

For this reason, another environment variable management tool was born: fuck-env, which means "fuck environment variable" and supports all the above functions.

fuck-env installation and use

npm install fuck-env

If there is one containing package.json and main.js The project of the file, the file code is as follows:

package.json

{
"name": "fuck-env-demo",
"config": {
"PORT": 8000,
"APP_NAME": "$npm_package_name"
},
"scripts": {
"start": "fuck-env node main.js"
},
"dependencies": {
"fuck-env": "*"
}
}

main.js

console.log(process.env.PORT) // 8080
console.log(process.env.APP_NAME) // fuck-env-demo

执行fuck-env PORT=8080 npm start后,输出“8080”和“fuck-env-demo”,不论是在 Windows 还是 POSIX(macOS、Linux 等)系统中。

如果成员希望本地持久化自定义的端口号,可以新建一个 .env 文件(此文件须加入 .gitignore,不计入版本管理,格式为类 .ini 文件的简单键值对)。

.env

PORT=8080

以后只需执行npm start即可。此外 fuck-env 还提供了另一个命令行工具:fuck,用于快速设置本地环境变量。比如,如果成员又希望使用 9000 端口,可以在项目根目录下执行fuck set PORT 9000(需全局安装 fuck-env),此时项目目录下 .env 文件的内容即会变为“PORT=9000”,使用 fuck 命令在环境变量较多时非常方便。

当环境变量过多时,全部放置 package.json 的 config 字段也会显得臃肿。fuck-env 支持统一管理默认环境变量,只需将 config 字段下所有环境变量移至 default.env 文件(计入版本库)中即可。

以上内容就是如何更好的管理前端环境变量的方法,希望对大家有帮助。

相关推荐:

什么是环境变量?环境变量的作用

分享环境变量与文件查找实例

Linux设置和查看环境变量的方法

The above is the detailed content of A better way to manage front-end environment variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn