在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_ 开头的变量才会被读取。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?