Featured image of post Nix Recipe: Setup Nodejs

Nix Recipe: Setup Nodejs

Nix recipe to setup nodejs in a cross platform virtual nix environment

This is a nix recipe for building and running nodejs in a virtual nix environment.

Step 1: Create nodejs.nix

In your project folder, create a new file nodejs.nix and add following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{ nixpkgs ? import <nixpkgs> {}, version, sha256 }:

let
inherit (nixpkgs) python37 utillinux stdenv autoPatchelfHook fetchurl binutils-unwrapped patchelf xcbuild;
inherit (stdenv) mkDerivation;

in
mkDerivation {
inherit version;

name = "nodejs-${version}";
src = fetchurl {
  url = "https://nodejs.org/dist/v${version}/node-v${version}${if stdenv.isDarwin then "-darwin-x64" else "-linux-x64"}.tar.xz"; # this darwin/linux check doesn't work since sha is different for packages
  inherit sha256;
};

# Dependencies for building node.js (Python and utillinux on Linux, just Python on Mac)
buildInputs = with nixpkgs; [ xcbuild binutils-unwrapped patchelf glib python37 ] ++ stdenv.lib.optional stdenv.isLinux utillinux;
nativeBuildInputs = with nixpkgs; [ autoPatchelfHook ];

installPhase = ''
  echo "installing nodejs"
  mkdir -p $out
  cp -r ./ $out/
'';

meta = with stdenv.lib; {
  description = "Event-driven I/O framework for the V8 JavaScript engine";
  homepage = "https://nodejs.org";
  license = licenses.mit;
};

passthru.python = python37;
}

Note:

  • This will download the nodejs package depending on darwin or linux and build it.

Step 2: Create shell.nix

Add shell.nix with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
let
nixpkgs = import (builtins.fetchTarball https://github.com/NixOS/nixpkgs/archive/20.03.tar.gz) {
  overlays = [];
  config = {};
};

installNodeJS = import (./nodejs.nix) {
  inherit nixpkgs;
  version = "13.6.0";
  sha256 = "${if nixpkgs.stdenv.isDarwin then "0z64v76w8x02yg2fz2xys580m9mlwklriz1s5b0rxn569j4kwiya" else "166pm67i7qys3x6x1dy5qr5393k0djb04ylgcg8idnk7m0ai7w00"}";
};
frameworks = nixpkgs.darwin.apple_sdk.frameworks;


in
with nixpkgs;

stdenv.mkDerivation {
  name = "nodejs-env";
  buildInputs = [ installNodeJS ];

  nativeBuildInputs = [
    zsh
    vim
  ] ++ (
    stdenv.lib.optionals stdenv.isDarwin [
      frameworks.Security
      frameworks.CoreServices
      frameworks.CoreFoundation
      frameworks.Foundation
    ]
  );

  # Post Shell Hook
  shellHook = ''
  '';
}

Note:

  • Here, the nix packages are installed from 20.03 release.
  • NodeJS 13.6.0 version is installed, this is passed as argument. Different version can also be installed provided corresponding SHA is added.
  • All node packages can be installed via NPM in this environment.

Step 3: Run nix shell

Run below command to build and setup nodejs in a virtual environment.

1
nix-shell --pure shell.nix