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') });
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