1

Setting a custom path to a .env file is easy enough when using the require syntax pattern.

import { URL } from 'url';
config({ path: new URL('./models/.env', import.meta.url).pathname });
require('dotenv').config({ path: path.join(rootPath, '/models/.env') });

However, I recently added "type": "module", to my package.json file and I'm in the process of updating all of my code to use the new ES6 import syntax.

The dotenv page on NPM and README.md show how to load in es6 but not how to set a path.

import 'dotenv/config'

I've tried using .config after loading dotenv but that doesn't work.

import 'dotenv/config'
import { URL } from 'url';
config({ path: new URL('./models/.env', import.meta.url).pathname });
dotenv.config({ path: path.join(rootPath, '/models/.env') });

1 Answer 1

5

You can't use dotenv/config if you need to pass parameters. Use this approach instead (and also avoid __dirname):

env.js

import { URL } from 'url';
import { config } from 'dotenv';
config({ path: new URL('./models/.env', import.meta.url).pathname });

index.js

import './env'; // instead of import 'dotenv/config';
… // your other imports
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.