nrwl / nx

Smart Monorepos · Fast CI
https://nx.dev
MIT License
23.57k stars 2.36k forks source link

@nrwl/nest VSCode breakpoints no longer working #14708

Open ZenSoftware opened 1 year ago

ZenSoftware commented 1 year ago

Current Behavior

I am getting unbound breakpoints in VSCode when trying to debug Nest with a fresh npx create-nx-workspace@latest. This just suddenly started occurring over the past 3 days with no real cause that I can narrow it down to.

image

Though creating a Nest app using @nestjs/cli with npx @nestjs/cli@latest new and serving with nest start --debug with the same launch.json seems to work. It seems to be something specific to Nx.

Expected Behavior

Breakpoints should work

GitHub Repo

No response

Steps to Reproduce

  1. Created a fresh Nest integrated monorepo using npx create-nx-workspace@latest
  2. Launch VSCode with all extensions disabled via code . --disable-extensions
  3. Add the following .vscode/launch.json
    {
    "version": "0.2.0",
    "configurations": [
    {
      "name": "nest",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "restart": true
    }
    ]
    }
  4. Set a breakpoint, nx serve api and start VSCode debugger

Nx Report

Node : 18.13.0
OS   : win32 x64
npm  : 8.19.3

nx : 15.6.3
@nrwl/angular : Not Found
@nrwl/cypress : Not Found
@nrwl/detox : Not Found
@nrwl/devkit : 15.6.3
@nrwl/esbuild : Not Found
@nrwl/eslint-plugin-nx : 15.6.3
@nrwl/expo : Not Found
@nrwl/express : Not Found
@nrwl/jest : 15.6.3
@nrwl/js : 15.6.3
@nrwl/linter : 15.6.3
@nrwl/nest : 15.6.3
@nrwl/next : Not Found
@nrwl/node : 15.6.3
@nrwl/nx-cloud : Not Found
@nrwl/nx-plugin : Not Found
@nrwl/react : Not Found
@nrwl/react-native : Not Found
@nrwl/rollup : Not Found
@nrwl/schematics : Not Found
@nrwl/storybook : Not Found
@nrwl/web : Not Found
@nrwl/webpack : 15.6.3
@nrwl/workspace : 15.6.3
@nrwl/vite : Not Found
typescript : 4.8.4
---------------------------------------
Local workspace plugins:
---------------------------------------
Community plugins:

Failure Logs

No response

Additional Information

No response

rudfoss commented 6 months ago

@MilanKovacic Thanks for the detailed explanation.

I was trying to get it working using the "auto attach" feature so that all you needed to do to get debugging running was to use a pre-defined task that basically ran nx serve for that project. In my current workspace I don't have a launch.json file and was trying to avoid having to create one.

I'm generally not a big fan of having to start the app then attach the debugger as a separate manual step as you may not be able to break on the very first line of code. I'm sure that starting and attaching can be done using a single launch.json configuration, but it seemed even easier if I could simply auto-attach and then use the nx serve target as normal.

MilanKovacic commented 6 months ago

I've accidentally skipped over the "auto" part of the attach, so I was confused why the solution was not working. Hopefully, the fix lands soon so that both approaches work without customizations.

MilanKovacic commented 5 months ago

Hi @ndcunningham, is there any progress on implementing this so that debugging works out of the box? In the comment above (https://github.com/nrwl/nx/issues/14708#issuecomment-2087961713) I detailed the problems and the potential fix.

minikdev commented 4 months ago

bump. the debugger is not working without the solution @MilanKovacic (thanks) provided. my "nx" version is 19.0.6

rlarac commented 2 months ago

The debugger is still not working without the workaround/solution provided by @rudfoss in Nx 19.5.7.

gloomweaver commented 1 month ago

Nx 19.5.7 Made it work with providing outFiles in launch json

webpack.config.js

const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin')
const { join } = require('path')

module.exports = {
  output: {
    path: join(__dirname, '../../../dist/backend/apps/api'),
  },

  plugins: [
    new NxAppWebpackPlugin({
      target: 'node',
      compiler: 'tsc',
      main: './src/main.ts',
      tsConfig: './tsconfig.app.json',
      assets: ['./src/assets'],
      generatePackageJson: true,
      optimization: false,
      sourceMap: true,
      outputHashing: 'none',
    }),
  ],
}

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug API",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "restart": true,
      "cwd": "${workspaceFolder}/backend/apps/api",
      "outFiles": ["${workspaceFolder}/dist/**/*.(m|c|)js", "!**/node_modules/**"]
    }
  ]
}
adamwdennis commented 1 month ago

Got it working like so:

.vscode/launch.json:

   {
      "name": "Attach to API (must be running)",
      "type": "node",
      "request": "attach",
      "address": "localhost",
      "port": 9229,
      "restart": true,
      "sourceMaps": true
    }

apps/api/project.json

"targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "defaultConfiguration": "production",
      "options": {
        "target": "node",
        "compiler": "tsc",
        "outputPath": "dist/apps/api",
        "main": "apps/api/src/main.ts",
        "tsConfig": "apps/api/tsconfig.app.json",
        "webpackConfig": "apps/api/webpack.config.js",
        "generatePackageJson": true,
        "sourceMap": true
      },
      "configurations": {
        "production": {
          "optimization": true,
          "extractLicenses": true,
          "inspect": false
        },
        "development": {
          "optimization": false
        }
      }
    },
    "serve": {
      "executor": "@nx/js:node",
      "defaultConfiguration": "development",
      "dependsOn": ["build"],
      "options": {
        "buildTarget": "api:build",
        "runBuildTargetDependencies": false,
        "port": 9229
      },
      "configurations": {
        "development": {
          "buildTarget": "api:build:development"
        },
        "production": {
          "buildTarget": "api:build:production"
        }
      }
    },

apps/api/tsconfig.app.json

  {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../dist/apps/api",
    "module": "commonjs",
    "types": ["node"],
    "emitDecoratorMetadata": true,
    "target": "es2021",
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true
  },
  "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
  "include": ["src/**/*.ts"]
}

apps/api/webpack.config.js

const { composePlugins, withNx } = require('@nx/webpack');
const path = require('path');

module.exports = composePlugins(withNx(), (config) => {
  config.output.devtoolModuleFilenameTemplate = function (info) {
    const rel = path.relative(process.cwd(), info.absoluteResourcePath);
    return `webpack:///./${rel}`;
  };
  config.optimization = {
    minimize: false,
  };
  return config;
});

package.json


   "scripts": {
      "serve:api": "NODE_OPTIONS='inspect' NODE_ENV=development ENVIRONMENT=local yarn nx run api:serve:development",
      ...
      }
treefitty commented 1 month ago

There is a piece of wall next to me with a nice size "my head" imprinted on it.... no matter what combination of the sorcery mentioned so far has worked despite from all accounts everything looking like it should be working 🥺

image

Both unit tests and app serving fail to connect, however when serving the app it does seem as though the Nx Node processes are connecting..... so it's close (at least it's doing something!)

image

My stack is vscode, node@20.5.1, nx@19.7.3, pnpm@9.10.0, vitest@2.1.1 & nx/webpack@19.7.3

Playjasb2 commented 1 month ago

This solution worked for me.

I am using VS Code, with pnpm@9.7.1, nx@19.6.1, node v22, and @nx/webpack@19.6.1.

sudharsan-gandhi commented 1 month ago

solution:

Project.json

set the project.json build option to run in development. By default, --node-env is always in production. source code: add build configuration for development to override node-env

screenshot:

image

pasted below to copy-paste:

    "build": {
      "configurations": {
        "development": {
          "args": ["--node-env=development"]
        }
      }
    }

web.config.js

change webpack.config.js to set sourcemap to true if not production build.

screenshot:

image

pasted below to copy-paste:

const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');
const { join } = require('path');

module.exports = (env, argv) => {
  console.log("env", env);
  console.log("argv", argv);
  return {
    output: {
      path: join(__dirname, '../../dist/app-dir'),
    },
    plugins: [
      new NxAppWebpackPlugin({
        target: 'node',
        compiler: 'tsc',
        main: './src/main.ts',
        tsConfig: './tsconfig.app.json',
        assets: ['./src/assets'],
        optimization: false,
        outputHashing: 'none',
        generatePackageJson: true,
        sourceMap: process.env['NODE_ENV'] !== 'production',
        verbose: process.env['NODE_ENV'] !== 'production'
      }),
    ],
  }
};

launch.json

finally add launch.json configuration just basic configuration is sufficient.

screenshot:

image

pasted below to copy-paste:

{
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": " base - Server",
      // "resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "runtimeArgs": [
        "nx",
        "run",
        "app-name:serve:development"
      ],
      "outputCapture": "std",
      "internalConsoleOptions": "openOnSessionStart",
      "autoAttachChildProcesses": true,
      "console": "internalConsole",
      "cwd": "${workspaceFolder}/ogon/api/"
    },
  ]
}

Note: please change the app name and pnpm to the required package manager. Also, append "development" to "app-name:serve" since "app-name:serve" is a production build and sourceMap will be false.