|
1 | | -# Repo of examples for Hermeto docs |
| 1 | +# npm example |
2 | 2 |
|
3 | | -Individual examples each live in their own branch (e.g. the basic `pip` example is in |
4 | | -the 'pip-basic' branch) |
| 3 | +This example demonstrates using Hermeto with a simple Node.js app that uses npm for dependency management. |
| 4 | + |
| 5 | +## Pre-fetch dependencies |
| 6 | + |
| 7 | +The `package-lock.json` file in this repo specifies which npm packages to download. |
| 8 | +Run Hermeto to pre-fetch the dependencies into a local output directory: |
| 9 | + |
| 10 | +```shell |
| 11 | +hermeto fetch-deps --source . --output ./hermeto-output '{"type": "npm"}' |
| 12 | +``` |
| 13 | + |
| 14 | +## Generate environment variables |
| 15 | + |
| 16 | +Generate an environment file so you can pass the right settings to `npm install`: |
| 17 | + |
| 18 | +```shell |
| 19 | +hermeto generate-env ./hermeto-output -o ./hermeto.env --for-output-dir /tmp/hermeto-output |
| 20 | +``` |
| 21 | + |
| 22 | +Currently Hermeto does not require any environment variables for npm, but this |
| 23 | +may change in the future, so it is recommended to always generate this file. |
| 24 | + |
| 25 | +## Inject project files |
| 26 | + |
| 27 | +Next, inject the project files so that remote npm tarball URLs are rewritten to |
| 28 | +point at the locally fetched artifacts: |
| 29 | + |
| 30 | +```shell |
| 31 | +hermeto inject-files ./hermeto-output --for-output-dir /tmp/hermeto-output |
| 32 | +``` |
| 33 | + |
| 34 | +After this step, entries in `package-lock.json` like: |
| 35 | + |
| 36 | +```diff |
| 37 | +- "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", |
| 38 | ++ "resolved": "file:///tmp/hermeto-output/deps/npm/accepts-1.3.8.tgz", |
| 39 | +``` |
| 40 | + |
| 41 | +will point to files inside the mounted Hermeto output directory instead of the network. |
| 42 | + |
| 43 | +## Build the application image |
| 44 | + |
| 45 | +The `Containerfile` in this repo uses the `node:18` base image and runs `npm install` |
| 46 | +inside the container. With the injected files and environment file in place, the |
| 47 | +install step can run without network access. |
| 48 | + |
| 49 | +Build the image while mounting the Hermeto data: |
| 50 | + |
| 51 | +```shell |
| 52 | +podman build . \ |
| 53 | + --volume "$(realpath ./hermeto-output)":/tmp/hermeto-output:Z \ |
| 54 | + --volume "$(realpath ./hermeto.env)":/tmp/hermeto.env:Z \ |
| 55 | + --network none \ |
| 56 | + --tag npm-basic-example |
| 57 | +``` |
| 58 | + |
| 59 | +## Run the container |
| 60 | + |
| 61 | +```shell |
| 62 | +podman run -it --init -p 9000:9000 npm-basic-example |
| 63 | +``` |
| 64 | + |
| 65 | +Then open `http://localhost:9000` in your browser to reach the app. |
0 commit comments