如何访问和转换环境变量
🌐 How to access and cast environment variables
在大多数用例中,环境之间会有不同的配置(例如数据库凭据)。
🌐 In most use cases there will be different configurations between environments (e.g. database credentials).
与其将这些凭据写入配置文件,不如在应用根目录的 .env 文件中定义变量:
🌐 Instead of writing those credentials into configuration files, variables can be defined in a .env file at the root of the application:
# path: .env
DATABASE_PASSWORD=acme
要自定义要加载的 .env 文件路径,请在启动应用之前设置一个名为 ENV_PATH 的环境变量:
🌐 To customize the path of the .env file to load, set an environment variable called ENV_PATH before starting the application:
ENV_PATH=/absolute/path/to/.env npm run start
访问环境变量
🌐 Accessing environment variables
在 .env 文件中定义的变量可以在配置文件和应用文件中的任何地方使用 process.env.{variableName} 访问。
🌐 Variables defined in the .env file are accessible using process.env.{variableName} anywhere in configuration and application files.
在配置文件中,env() 工具允许定义默认值和转换值:
🌐 In configuration files, a env() utility allows defining defaults and casting values:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
connections: {
default: {
settings: {
password: env('DATABASE_PASSWORD'),
},
},
},
});
export default ({ env }) => ({
connections: {
default: {
settings: {
password: env('DATABASE_PASSWORD'),
},
},
},
});
语法 property-name: env('VAR', 'default-value') 使用存储在 .env 文件中的值。如果在 .env 文件中没有指定值,则使用默认值。
🌐 The syntax property-name: env('VAR', 'default-value') uses the value stored in the .env file. If there is no specified value in the .env file the default value is used.
设置环境变量
🌐 Casting environment variables
env() 工具可用于将环境变量转换为不同类型:
🌐 The env() utility can be used to cast environment variables to different types:
// Returns the env if defined without casting it
env('VAR', 'default');
// Cast to integer (using parseInt)
env.int('VAR', 0);
// Cast to float (using parseFloat)
env.float('VAR', 3.14);
// Cast to boolean (check if the value is equal to 'true')
env.bool('VAR', true);
// Cast to JS object (using JSON.parse)
env.json('VAR', { key: 'value' });
// Cast to array (syntax: ENV_VAR=[value1, value2, value3] | ENV_VAR=["value1", "value2", "value3"])
env.array('VAR', [1, 2, 3]);
// Cast to date (using new Date(value))
env.date('VAR', new Date());
// Returns the env matching oneOf union types
env.oneOf('UPLOAD_PROVIDER', ['local', 'aws'], 'local')