Node.js: Difference between revisions

Onny (talk | contribs)
Cleanup page
Makefu (talk | contribs)
m update link to homepage-dashboard package
 
(6 intermediate revisions by 6 users not shown)
Line 1: Line 1:
__TOC__
__TOC__


[https://nodejs.org Node.js] is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code on the server side. Built on the V8 JavaScript engine, it enables the creation of scalable and high-performance applications, particularly for real-time web services.
[https://nodejs.org Node.js] is an open-source, cross-platform [[JavaScript]] runtime environment that allows developers to execute JavaScript code on the server side. Built on the V8 JavaScript engine, it enables the creation of scalable and high-performance applications, particularly for real-time web services.


== Setup ==
== Setup ==
Line 9: Line 9:


See <code>nix search nixpkgs nodejs</code> for additional versions like <code>nodejs-12_x</code>, etc.
See <code>nix search nixpkgs nodejs</code> for additional versions like <code>nodejs-12_x</code>, etc.
== Packaging ==
=== 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."
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>.
<syntaxhighlight lang="json">
{
  "bin": {
    "my-node-script": "main.js"
  }
}
</syntaxhighlight>
==== Packaging electron applications ====
When trying to <code>npm i</code> electron, by default electron will try to download binaries from the internet, which does not work in the Nix sandbox. To stop it from trying to access the internet, set the environment variable <code>ELECTRON_SKIP_BINARY_DOWNLOAD = "1";</code>.
For examples of packaging electron applications, search [https://github.com/search?q=buildNpmPackage+electron+repo%3ANixOS%2Fnixpkgs&type=code&l=NixOS%2Fnixpkgs Nixpkgs] for the terms "buildNpmPackage" and "electron".
=== Packaging with <code>yarn2nix</code> ===
yarn2nix uses the yarn nodejs tool to create a file called yarn.lock, which in return can be used by yarn2nix to generate a usable yarn expression.
This is what was needed to convert a small application server  [https://git.shackspace.de/rz/muellshack/tree/3be09715911628b164fa1cf346387555ca26a5b1 shackspace muellshack]:
<syntaxhighlight lang="console">
$ nix-shell -p yarn yarn2nix
$ yarn install
# creates yarn.lock
$ yarn2nix > yarn.nix
$ vim package.json
# add:    "bin": "app.js",
$ cat > default.nix <<EOF
with (import <nixpkgs> {});
rec {
  muellshack = mkYarnPackage {
    name = "muellshack";
    src = ./.;
    packageJSON = ./package.json;
    yarnLock = ./yarn.lock;
    yarnNix = ./yarn.nix;
  };
}
EOF
$ sed -i '1i#!/usr/bin/env node' app.js
$ chmod +x app.js
$ nix-build
$ result/bin/muellshack
</syntaxhighlight>
The complete diff can be found at [https://git.shackspace.de/rz/muellshack/commit/f5e498acd47695c4947dc1b5ddebfad2eee8d653 the respective diff]


== Troubleshooting ==
== Troubleshooting ==
Line 173: Line 261:
</syntaxhighlight>You can take a look at what fonts are available in the Nix <code>google-fonts</code> package by calling:<syntaxhighlight lang="shell">
</syntaxhighlight>You can take a look at what fonts are available in the Nix <code>google-fonts</code> package by calling:<syntaxhighlight lang="shell">
ls -ahl $(nix build --no-link --print-out-paths nixpkgs#google-fonts)/share/fonts/truetype/
ls -ahl $(nix build --no-link --print-out-paths nixpkgs#google-fonts)/share/fonts/truetype/
</syntaxhighlight>Take a look at https://github.com/NixOS/nixpkgs/blob/master/pkgs/servers/homepage-dashboard/default.nix for further workarounds for Nextjs in Nix.
</syntaxhighlight>Take a look at [https://github.com/NixOS/nixpkgs/blob/8358fd43a66594d8b3445d87006185fa76d4be6e/pkgs/by-name/ho/homepage-dashboard/package.nix homepage-dashboard package in nixpkgs] for further workarounds for Nextjs in Nix.


== Tips and tricks ==
== Tips and tricks ==
=== 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."
'''To better understand what happens under the hood and see the latest features see'''
https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/node/build-npm-package/default.nix
==== Packaging electron applications ====
When trying to <code>npm i</code> electron, by default electron will try to download binaries from the internet, which does not work in the Nix sandbox. To stop it from trying to access the internet, set the environment variable <code>ELECTRON_SKIP_BINARY_DOWNLOAD = "1";</code>.
For examples of packaging electron applications, search [https://github.com/search?q=buildNpmPackage+electron+repo%3ANixOS%2Fnixpkgs&type=code&l=NixOS%2Fnixpkgs Nixpkgs] for the terms "buildNpmPackage" and "electron".
=== Packaging with <code>yarn2nix</code> ===
yarn2nix uses the yarn nodejs tool to create a file called yarn.lock, which in return can be used by yarn2nix to generate a usable yarn expression.
This is what was needed to convert a small application server  [https://git.shackspace.de/rz/muellshack/tree/3be09715911628b164fa1cf346387555ca26a5b1 shackspace muellshack]:
<syntaxHighlight lang=console>
$ nix-shell -p yarn yarn2nix
$ yarn install
# creates yarn.lock
$ yarn2nix > yarn.nix
$ vim package.json
# add:    "bin": "app.js",
$ cat > default.nix <<EOF
with (import <nixpkgs> {});
rec {
  muellshack = mkYarnPackage {
    name = "muellshack";
    src = ./.;
    packageJSON = ./package.json;
    yarnLock = ./yarn.lock;
    yarnNix = ./yarn.nix;
  };
}
EOF
$ sed -i '1i#!/usr/bin/env node' app.js
$ chmod +x app.js
$ nix-build
$ result/bin/muellshack
</syntaxHighlight>
The complete diff can be found at [https://git.shackspace.de/rz/muellshack/commit/f5e498acd47695c4947dc1b5ddebfad2eee8d653 the respective diff]
=== Example nix flake shell for Node.js development ===
=== Example nix flake shell for Node.js development ===
`flake.nix` example:
[[Flake]] example: (Note: the `${&amp;lt;nixpkgs&amp;gt;}` needs to be replaced by `${<nixpkgs>}`
<syntaxhighlight lang="nix>
{{file|flake.nix|nix|
<nowiki>
{
{
   description = "example-node-js-flake";
   description = "example-node-js-flake";
Line 259: Line 305:
}
}


</syntaxhighlight>
</nowiki>
}}


=== Using nodePackages with a different node version ===
=== Using nodePackages with a different node version ===
Line 272: Line 319:
v16.17.1
v16.17.1
</pre>
</pre>
=== Override NodeJS package ===
Overriding a Nix package which is based on ''buildNpmPackage'' can be challeging because not only the source hash has to get changed but sometimes also the ''package-lock.json'' file and the ''npmDepsHash''.
Unfortunately it is not possible to directly access and change ''npmDepsHash'' inside ''overrideAttrs'', so this is an example workaround for changing the version, ''package-lock.json'' and hashes of the package ''eslint'':<syntaxhighlight lang="nix">
environment.systemPackages = [
  (eslint.overrideAttrs (oldAttrs: rec {
    version = "8.57.0";
    src = fetchFromGitHub {
      owner = "eslint";
      repo = "eslint";
      rev = "refs/tags/v${version}";
      hash = "sha256-nXlS+k8FiN7rbxhMmRPb3OplHpl+8fWdn1nY0cjL75c=";
    };
    postPatch = ''
      cp ${./package-lock.json} package-lock.json
    '';
    npmDepsHash = "sha256-DiXgAD0PvIIBxPAsdU8OOJIyvYI0JyPqu6sj7XN94hE=";
    npmDeps = pkgs.fetchNpmDeps {
      src = lib.fileset.toSource {
        root = ./.;
        fileset = lib.fileset.unions [
          ./package-lock.json
          ./package.json
        ];
      };
      name = "eslint-${version}-npm-deps";
      hash = npmDepsHash;
    };
  }))
];
</syntaxhighlight>


== External Links ==
== External Links ==
Line 277: Line 356:


=== References ===
=== References ===
[[Category:JavaScript]]