Prepare applications for deployment via CI
A common approach to deploying applications is via docker containers. Some applications can be built into bundles that are environment agnostic, while others depend on OS-specific packages being installed. For these situations, having just bundled code is not enough, we also need to have package.json
.
Nx supports the generation of the project's package.json
by identifying all the project's dependencies. The generated package.json
is created next to the built artifacts (usually at dist/apps/name-of-the-app
).
Additionally, we should generate pruned lock file according to the generated package.json
. This makes the installation in the container significantly faster as we only need to install a subset of the packages.
Supported executors
The @nx/webpack:webpack
executor supports the generatePackageJson
flag which generates both package.json
as well as the lock file.
Some executors automatically generate output package.json
and the lock file generation is supported using the generateLockfile
flag:
@nx/js:swc
@nx/js:tsc
@nx/next:build
Using a custom executor
If you are using a custom executor or an executor that does not support generatePackgeJson
or generateLockfile
flags, you can still use Nx to generate package.json
and the lock file. The createPackageJson
and createLockFile
functions are exported from @nx/devkit
:
1import { createPackageJson, createLockFile } from '@nx/devkit';
2import { writeFileSync } from 'fs';
3
4export default async function buildExecutor(
5 options: Schema,
6 context: ExecutorContext
7) {
8 // ...your executor code
9
10 const packageJson = createPackageJson(
11 context.projectName,
12 context.projectGraph,
13 {
14 root: context.root,
15 isProduction: true, // We want to strip any non-prod dependencies
16 }
17 );
18
19 // do any additional manipulations to "package.json" here
20
21 const lockFile = createLockFile(packageJson);
22 writeJsonFile(`${options.outputPath}/package.json`, builtPackageJson);
23 writeFileSync(`${options.outputPath}/${packageLockFileName}}`, lockFile, {
24 encoding: 'utf-8',
25 });
26
27 // any subsequent executor code
28}
29