You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发模式下使用Nx时,如何让Webpack打包代码显示源文件链接

Nx + Express 开发模式错误栈指向打包文件的解决方法

问题场景

在包含Express应用的Nx项目中,执行nx serve my-app启动开发模式时,错误栈追踪指向Webpack打包后的文件路径,而非实际源文件:

TypeError: Cannot read properties of undefined (reading 'id')
    at /myproject/dist/apps/myapp/webpack:/src/main.ts:133:39
    at /myproject/node_modules/fp-ts/lib/Chain.js:15:103
    at /myproject/node_modules/fp-ts/lib/EitherT.js:83:97
    at /myproject/node_modules/fp-ts/lib/ReaderT.js:24:97
    at /myproject/node_modules/fp-ts/lib/Task.js:133:41

但项目中使用的tslog日志工具可正常显示正确的源文件路径:

ï [2023-09-26 14:26:23.681]    INFO    MyApp      [/libs/domain/app/src/MyApp.ts:347]
└» Starting scheduler...
ï [2023-09-26 14:26:23.688]    DEBUG   MyApp      [/libs/domain/operations/src/operation/RegisterOrUpdateUser.ts:27]
└» Registering or updating user with email <...>.
ï [2023-09-26 14:26:23.692]    DEBUG   MyApp      [/libs/domain/operations/src/operation/RegisterOrUpdateUser.ts:33]
└» User with email <...> doesn't exist, creating user.

已尝试以下无效配置:

  • 在project.json中添加"sourceMap": true
  • 在webpack.config.js中手动配置source mapping

解决方案

1. 完善Nx的sourcemap配置

在项目的project.json中,同时确保build和serve目标的sourcemap配置正确:

{
  "targets": {
    "build": {
      "options": {
        "sourceMap": {
          "scripts": true,
          "styles": false,
          "vendor": false
        }
      }
    },
    "serve": {
      "options": {
        "sourceMap": true,
        "webpackConfig": "apps/my-app/webpack.config.js"
      }
    }
  }
}

2. 配置Webpack开发环境的devtool

在自定义webpack.config.js中,针对开发模式设置合适的devtool选项,推荐使用eval-cheap-module-source-map(兼顾性能和映射精度):

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

module.exports = composePlugins(withNx(), (config) => {
  if (config.mode === 'development') {
    config.devtool = 'eval-cheap-module-source-map';
  }
  return config;
});

3. 启用Node.js源映射解析

修改project.json的serve目标,添加--enable-source-maps参数让Node.js自动解析sourcemap:

{
  "serve": {
    "executor": "@nx/js:node",
    "options": {
      "buildTarget": "my-app:build",
      "sourceMap": true,
      "args": ["--enable-source-maps"]
    }
  }
}

也可直接在启动命令中追加参数:

nx serve my-app --args="--enable-source-maps"

4. 检查TypeScript配置

确保tsconfig.app.json中启用sourcemap相关选项:

{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSourceMap": false,
    "inlineSources": true
  }
}

5. 清理缓存后重启服务

执行命令清理Nx缓存,避免旧打包文件干扰:

nx reset

随后重新启动服务:nx serve my-app


内容的提问来源于stack exchange,提问作者Adam A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:30:04