在nodejs中如何读取.env和.env.local

您应该能够在NextJS中使用process.env.<VARIABLE_NAME>访问env变量。
如果这对你不起作用,请分享你所做的一切以及结果。

 

 

 

 

如果存在.env.local文件,则dotenv将覆盖.env

dotenv.config();

dotenv.config({ path: `.env.local`, override: true });

 

 

 

 

 

 

读取.env

关键行:connection: process.env.DB_URL

复制代码
import dotenv from 'dotenv'
dotenv.config()

const Config = {
  client: 'pg',
  connection: process.env.DB_URL,
  acquireConnectionTimeout: 5000,
  pool: {
    min: 2, // Minimum number of connections in the pool
    max: 20, // Maximum number of connections in the pool
    // propagateCreateError: false, // enabling knex to automatically reconnect on create connection failure instead of throwing the error.
  },
  migrations: {
    directory: './migrations',
  },
  seeds: { directory: './seeds' },
}

const knexConfig = { Dev: Config, Beta: Config, Prod: Config }

export default knexConfig
复制代码

 

 

读取.env.local

关键行:connection: process.env.local.DB_URL

复制代码
import dotenv from 'dotenv'
dotenv.config()

const Config = {
  client: 'pg',
  connection: process.env.local.DB_URL,
  acquireConnectionTimeout: 5000,
  pool: {
    min: 2, // Minimum number of connections in the pool
    max: 20, // Maximum number of connections in the pool
    // propagateCreateError: false, // enabling knex to automatically reconnect on create connection failure instead of throwing the error.
  },
  migrations: {
    directory: './migrations',
  },
  seeds: { directory: './seeds' },
}

const knexConfig = { Dev: Config, Beta: Config, Prod: Config }

export default knexConfig
复制代码

 

 

 

在 Vue中使用 env,底层原理还是 vue-cli-service 内部集成了对 .env 配置文件的处理,并加载到 process.env 上。

加载文件优先级: .env.development.local > .env.development > .env;
可手动指定mode。
只有 NODE_ENV,BASE_URL 和以 VUE_APP_ 开头的变量才会被读取。

 

posted @   走走停停走走  Views(1062)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示