Closed ralyodio closed 1 year ago
Using the same way as documented for dotenv
(see here) seems to work just fine:
// As early as possible
import 'dotenv-flow/config';
@lucsky that wouldn't work unless https://github.com/kerimdzhanov/dotenv-flow/pull/57 is merged
@perrin4869 weird, I guess I'm lucky then because it works perfectly fine for me in two different projects... 🤔
Do you have type module in package.json?
This worked for me in a ESM file:
import { foo } from "foo";
import { bar } from "./path/to/bar";
(await import("dotenv-flow")).config();
console.log(process.env.HELLO);
Because static imports are async by nature, I’m not sure if placing await
before imports will guarantee correct process.env
values in foo
and ./path/to/bar
. Needs checking.
FWIW: even though #57 hasn't been merged, I've had luck using this within an ES module:
import "dotenv-flow/config.js";
The ".js"
is necessary because of this (see 2nd and 3rd bullet points). One of those tricky/annoying differences with ES modules in a pure Node context versus the Webpack context many of us are more familiar with.
I'm also able to get @kachkaev's method to work, but other imported module files are only able to access the vars if they're imported after dotenv and also use dynamic import()
:
// probably doesn't matter where this goes since it's a package and doesn't use process.env internally
const foo = await import("foo");
(await import("dotenv-flow")).config(); // has to come before the import below
const bar = await import("./path/to/bar.js"); // process.env used in this file
I think this is because nodejs support that, check https://nodejs.org/api/esm.html#commonjs-namespaces
When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax:
My config/env.ts
file doesn't import anything else so this works for me to set the default NODE_ENV
in an ESM package (with `"type": "module" in package.json):
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = "development";
}
(await import("dotenv-flow")).config();
However the following would not work in an ESM package:
(await import("dotenv-flow")).config({
node_env: process.env.NODE_ENV,
default_node_env: "development",
});
Hello gents,
Sorry for being late to the party 😅,
Let me check #57 by @perrin4869 (thanks a lot for the PR!), for now, you can try this:
import * as dotenvFlow from 'dotenv-flow';
dotenvFlow.config();
I'll update the README appropriately once we check and merge the PR (* as
may not be needed after merging).
Is this correct?