【问题标题】:Passing .env consts to inner directories将 .env 常量传递给内部目录
【发布时间】:2020-12-14 15:01:07
【问题描述】:

我的 ConfigKnex.ts 文件看起来像

require("ts-node/register");
import { config } from "dotenv";
config();

const { DATABASE_URL } = process.env;
console.log({ DATABASE_URL });

export const development = {
    client: "postgresql",
    connection: DATABASE_URL,
};

我的文件目录是这样的

server
- lib
-- somefiles.js
- package.json
- .env

如果我运行 "db:seed": "npx knex --knexfile ./ConfigKnex.ts seed:run" ,它可以工作。

如果我将 ConfigKnex 移动到 lib 文件夹下并运行 "db:seed": "npx knex --knexfile ./lib/ConfigKnex.ts seed:run",它不会。进一步调试后,我注意到如果我移动 ConfigKnex,DATABASE_URL 是未定义的。

为什么 ConfigKnex 只能获取本地的 .env 文件?有没有办法在没有中间文件的情况下将 .env consts 传递给 ConfigKnex?

【问题讨论】:

    标签: javascript typescript environment-variables knex.js


    【解决方案1】:

    您可以将路径传递给 dotenv.config()。 Node 的 path 模块可以解决您的问题并规范化路径。像这样的:

    import path from "path";
    import { config } from "dotenv";
    config({
      path: path.resolve(__dirname, "..", ".env"), // adjust path to your needs
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2020-05-01
      • 2023-03-15
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      相关资源
      最近更新 更多