nix-community / nix-direnv

A fast, persistent use_nix/use_flake implementation for direnv [maintainer=@Mic92 / @bbenne10]
MIT License
1.78k stars 101 forks source link

How do I load environment vairibale in .env automatically? #477

Closed ylbeethoven closed 6 months ago

ylbeethoven commented 6 months ago

Hi,

This tool is great for loading flake.nix or shell.nix but it is not clear how it could work like the standard direnv which loads .env automatically.

When I tried direnv allow, I am getting.

error .envrc file not found

Do I have to use a shell.nix to load environment variable?

bbenne10 commented 6 months ago

Just add the environment variable to your mkShell invocation. All non-recognized keys provided in the attrset argument given to mkShell will be exported as environment variables inside the spawned shell.

ylbeethoven commented 6 months ago

Just add the environment variable to your mkShell invocation. All non-recognized keys will be exported as environment variables.

Thanks for the reply.

I guess this confirms that this tool can not be used to load .env directly.

Do you mind sharing an simple example? I know below works but I am not too sure if it is the best way to do it.

# save this as shell.nix
{ pkgs ? import <nixpkgs> {}}:

pkgs.mkShell {
    shellHook = ''
      export VAR_NAME=abc
    '';
}
bbenne10 commented 6 months ago

We also don't reset the environment entirely. If your .envrc looks like this:

export FOO="bar"
export BAR="baz"
use flake

You'll end up with FOO and BAR in your environment.

You could also add dotenv_if_exists .env to load an existing .env file in the same directory as .envrc.

This is not a nix-direnv bug (or feature) and so I am closing this ticket,

bbenne10 commented 6 months ago

Do you mind sharing an simple example?

Not at all:

# save this as shell.nix
{ pkgs ? import <nixpkgs> {}}:

pkgs.mkShell {
    FOO="bar";
}

nix-direnv is not the tool that will be doing the .env loading. direnv does that. We simply provide an additional set of variables to load (or unset). This is really an intersection of three tools and their behaviors: