Node.js: Difference between revisions

Pigs (talk | contribs)
m Link to other pages
Arcstur (talk | contribs)
Packaging: example on how to package a npm package with flakes
Line 13: Line 13:


=== Packaging with <code>buildNpmPackage</code> ===
=== Packaging with <code>buildNpmPackage</code> ===
From the [https://nixos.org/manual/nixpkgs/stable/#javascript-tool-specific Nixpkgs manual]: "<code>buildNpmPackage</code> allows you to package npm-based projects in Nixpkgs without the use of an auto-generated dependencies file (as used in node2nix). It works by utilizing npm’s cache functionality – creating a reproducible cache that contains the dependencies of a project, and pointing npm to it."
From the [https://nixos.org/manual/nixpkgs/stable/#javascript-tool-specific Nixpkgs manual]: "<code>buildNpmPackage</code> allows you to package npm-based projects in Nixpkgs without the use of an auto-generated dependencies file (as used in node2nix). It works by utilizing npm’s cache functionality – creating a reproducible cache that contains the dependencies of a project, and pointing npm to it."


'''To better understand what happens under the hood and see the latest features see'''
To better understand what happens under the hood and see the latest features [https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/node/build-npm-package/default.nix see the build-npm-package source].
 
Here's a <code>flake.nix</code> example to build a node package from the current directory.
 
<syntaxhighlight lang="nix">
{
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
  };
 
  outputs = {
    self,
    nixpkgs,
  }: let
    pkgs = nixpkgs.legacyPackages."x86_64-linux";
  in {
    packages."x86_64-linux".default = pkgs.buildNpmPackage {
      pname = "my-node-script";
      version = "0.1.0";
      src = ./.;
      npmDepsHash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
    };
  };
}
</syntaxhighlight>
 
By default, the build phase runs the <code>build</code> script defined in <code>package.json</code>.
 
<syntaxhighlight lang="json">
{
  "scripts": {
    "build": "npm install"
  }
}
</syntaxhighlight>
 
The binaries created in this package are defined by the <code>bin</code> key in <code>package.json</code>. This example will result in a <code>my-node-script</code> binary being created that basically runs <code>node main.js</code>.


https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/node/build-npm-package/default.nix
<syntaxhighlight lang="json">
{
  "bin": {
    "my-node-script": "main.js"
  }
}
</syntaxhighlight>


==== Packaging electron applications ====
==== Packaging electron applications ====