Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate package.json on nx build / deployment

Tags:

nestjs

nrwl-nx

I've a monorepo using nx with multiple node/nestjs apps. Some of the apps doesn't require all the packages used in the other apps. Because it's a monorepo, I need to install all packages for every apps during the deployment.

Is there a way generate a package.json on build that would contain only the packages needed for the app that I'm building?

I've tryed to use "generate-package-json-webpack-plugin" to generate the package.json, but it only detect half the dependencies.

I've also tried to build a single js file containing all the apps, but it doesn't seem to work and always require tslib.

like image 775
N0Cloud Avatar asked Aug 22 '19 19:08

N0Cloud


2 Answers

After I look at the nx source code I found the answer.

Set generatePackageJson to true in workspace.json where <project-name>/targets/build/options.

This will generate you package.json with the necessary dependencies for your app.

Here example:

"node-api": {
      "root": "apps/node-api",
      "sourceRoot": "apps/node-api/src",
      "projectType": "application",
      "prefix": "node-api",
      "targets": {
        "build": {
          "executor": "@nrwl/node:build",
          "outputs": ["{options.outputPath}"],
          "options": {
            "showCircularDependencies": false,
            "outputPath": "dist/apps/node-api",
            "main": "apps/node-api/src/main.ts",
            "tsConfig": "apps/node-api/tsconfig.app.json",
            "assets": ["apps/node-api/src/assets"],
            "generatePackageJson": true <----------------------
          },
....
like image 116
Shlomi Levi Avatar answered Nov 19 '22 05:11

Shlomi Levi


Nx encourages a single-version policy and has a single package.json.

If the issue is that you are installing all the dependencies every time in CI before building then you might need to rely on the functionality provided by your CI system to cache these between runs - a lot of existing CI systems do provide these: * Gitlab: https://docs.gitlab.com/ee/ci/caching/ * CircleCI: https://circleci.com/docs/2.0/caching/ * Travis: https://docs.travis-ci.com/user/caching/

However this comes with its own set of issues (e.g. parallel jobs where one or more is changing the dependencies).

We can try to explore having a command in Nx: sort of a "affected:dep-install" that will detect which packages to install as part of the affected command. Please create an issue for it here: https://github.com/nrwl/nx/issues

like image 22
electrichead Avatar answered Nov 19 '22 05:11

electrichead