How do I setup the dotenv file in Node.js?

前端 未结 30 1177

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:



        
30条回答
  •  情深已故
    2020-12-07 15:03

    I had a problem also with .env variables not loading and being undefined.

    What I tried:

    index.js:

    import dotenv from 'dotenv';
    dotenv.config();
    import models from './models';
    

    models.js

    import Sequelize from 'sequelize';
    const sequelize = new Sequelize(
        process.env.DATABASE,
        process.env.DATABASE_USER,
        process.env.DATABASE_PASSWORD,
        {
            dialect: 'postgres',
        }
    );
    

    Apparently, because of how loading the imports works in nodejs, the import of models in index.js caused that the models.js was executed before dotenv.config(). Therefore I got undefined values from process.env.

    When I changed models.js to do the dotenv configuration like:

    import Sequelize from 'sequelize';
    import dotenv from 'dotenv';
    dotenv.config();
    const sequelize = new Sequelize(
        process.env.DATABASE,
        process.env.DATABASE_USER,
        process.env.DATABASE_PASSWORD,
        {
            dialect: 'postgres',
        }
    );
    

    it started to work!

提交回复
热议问题