首页 > 解决方案 > process.env 不显示 app.js 之外的变量

问题描述

应用程序.js

    import koa from 'koa';
    import http from 'http';
    import logger from 'koa-logger';
    import koaBody from 'koa-body';
    import dotenv from 'dotenv';
    import dotenvExpand from 'dotenv-expand';

    const config = dotenv.config();

    dotenvExpand(config);

    console.log(process.env); // Here I see all data which are in my .env file

    import { client } from '@pg'; // Inside this file I doesn't see this , but it still after initializing dotenv

@pg = db/connection/index.js

import { Client } from 'pg';

console.log(process.env.DATABASE_URL, 'fds'); // here I don't see the same ( all variables from .env file are undefined)

export const client = new Client({
  connectionString: process.env.DATABASE_URL
});

如果您需要更多信息,请告诉我。注意我在代码片段中的评论,这可能会有所帮助

标签: node.jsdotenv

解决方案


You need to invoke dotenv in every file you are calling a .env variable.

import dotenv from 'dotenv';
import { Client } from 'pg';

const config = dotenv.config();

console.log(process.env.DATABASE_URL, 'fds');

If you want to call dotenv in all your app files without calling it every time then you need to require it when you run your app:

node -r dotenv/config app.js

推荐阅读