canva-public/js2nix

Packaging a node package using js2nix

bromanko opened this issue · 2 comments

I've been building my node packages with buildNpmPackage. However, I'd like to switch to js2nix. buildNpmPackage relies upon a package-lock.json so seems inappropriate. How are others building packages with js2nix dependencies?

I ended up making a custom buildNpmPackage that skips the standard npm install step in favor of using the js2nix.nodeModules derivation.

{ lib, stdenv, buildPackages, nodejs, darwin }@_args:

{ name ? "${args.pname}-${args.version}", src ? null, srcs ? null
, sourceRoot ? null, nativeBuildInputs ? [ ], buildInputs ? [ ]
, npmBuildScript ? "build" # The script to run to build the project.
, nodejs ? _args.nodejs, npmDeps ? [ ] # Node.js dependencies derivation
, ... }@args:

let
  npmHooks = buildPackages.npmHooks.override { inherit nodejs; };
  inherit (npmHooks) npmBuildHook npmInstallHook;
in stdenv.mkDerivation (args // {
  inherit npmDeps npmBuildScript;

  nativeBuildInputs = nativeBuildInputs
    ++ [ nodejs npmBuildHook npmInstallHook nodejs.python ]
    ++ lib.optionals stdenv.isDarwin [ darwin.cctools ];
  buildInputs = buildInputs ++ [ nodejs ];

  postPatch = ''
    export HOME="$TMPDIR"
    cp -r ${npmDeps} node_modules
    chmod -R 700 node_modules
    patchShebangs node_modules
  '';

  strictDeps = true;

  # Stripping takes way too long with the amount of files required by a typical Node.js project.
  dontStrip = args.dontStrip or true;

  # Pruning often fails
  dontNpmPrune = args.dontNpmPrune or true;

  meta = (args.meta or { }) // {
    platforms = args.meta.platforms or nodejs.meta.platforms;
  };
})

Hey @bromanko, apologies for deferred reply, I noticed your messages a moment ago.

Regarding the initial question, I think js2nix supports yarn lock file of the version 1, only. So, in order to make use of js2nix you would need to use yarn@1 (aka classic) as your package manager, or make sure you provide yarn.lock file in the format of the yarn@1. It can be sort of converter or like. I would recommend to go with yarn@1.

About the packaging of your project. In not too sure what is happening in your code listing above. Can you explain what are you trying to do? I maybe can come up with some ideas on how to make it optimal.