如何用nx管理Dash+FastAPI混合repo?

解读

国内一线公司普遍把 Dash 仪表盘与 FastAPI 服务放在同一仓库,前者负责可视化,后者负责模型推理、数据接口与权限校验。面试官问“用 nx 管理”,核心是考察候选人能否在单仓(monorepo)里同时治理 Python 与 Node 两条技术栈,并解决以下痛点:

  1. 两种语言的任务(Dash 的 npm run build、FastAPI 的 uvicorn 启动)如何统一编排;
  2. 依赖隔离:Dash 前端组件用 Node 生态,FastAPI 用 Conda/pip,避免互相污染;
  3. 缓存与增量:CI 里只重建发生变更的子项目,节省云原生流水线时长;
  4. 规范落地:统一 lint、单测、构建、镜像打包命令,让数据科学、前端、后端三条职能线按同一套规则交付。

知识点

  1. Nx 插件体系:官方 @nx/js 支持 Node,社区 @nxlv/python 支持 Python,二者可在同一 nx.json 共存;
  2. Project Graph 与 Target:每个子项目声明 targets.build、targets.serve、targets.test,Nx 通过 nx affected 计算依赖图,实现增量;
  3. 依赖策略:前端项目用 package.json + pnpm-lock.yaml,Python 项目用 pyproject.toml + poetry.lock,在根目录通过 nx 的 inputs 与 namedInputs 分别指纹;
  4. 任务管道(pipeline):在 nx.json 里定义 build 依赖 lint 与 test,并设置 runner=@nx-cloud 把缓存上传到国内云厂商对象存储,实现秒级命中;
  5. 容器化:每个子项目输出独立 Dockerfile,Nx 的 target.docker-build 产物为镜像 tar,再由 GitLab CI 或 GitHub Actions 推送到阿里云 ACR/腾讯云 TCR;
  6. 本地开发:通过 nx serve dash-app 启动 Dash 的 Webpack 热更新,同时 nx serve api 启动 FastAPI,Nx 在 proxy.conf.json 里把 /api 转发到 localhost:8000,实现前后端联调;
  7. 发布策略:利用 nx release 自动生成变更日志,按语义化版本同时打 Tag,Dash 静态资源走 CDN,FastAPI 镜像走 Kubernetes Helm 灰度。

答案

步骤一:初始化 monorepo

npx create-nx-workspace@latest dash-fastapi-monorepo \
  --preset=ts --pm=pnpm --nxCloud=true
cd dash-fastapi-monorepo
pnpm add -D @nxlv/python

步骤二:创建子项目

nx g @nxlv/python:app fastapi-service --directory=apps/api \
  --moduleName=app.main:app --port=8000
nx g @nx/js:lib dash-core --directory=libs/dash-core
nx g @nx/react:app dash-app --directory=apps/dash --style=css

步骤三:配置依赖隔离
在 apps/api/pyproject.toml 中写入

[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.110"
uvicorn = {extras = ["standard"], version = "^0.29"}
pandas = "^2.2"
plotly = "^5.22"

在 apps/dash/package.json 中写入

{
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "@plotly/dash": "^2.17.1"
  }
}

步骤四:声明 targets
apps/api/project.json

{
  "name": "fastapi-service",
  "targets": {
    "serve": {
      "executor": "@nxlv/python:run-commands",
      "options": {
        "command": "poetry run uvicorn app.main:app --reload --port 8000"
      }
    },
    "test": {
      "executor": "@nxlv/python:pytest",
      "outputs": ["{workspaceRoot}/coverage/apps/api"],
      "options": {"args": "--cov=app"}
    },
    "docker-build": {
      "executor": "@nx/docker:build",
      "options": {
        "file": "apps/api/Dockerfile",
        "tags": ["registry.cn-hangzhou.aliyuncs.com/dp/api:{version}"]
      }
    }
  }
}

apps/dash/project.json

{
  "name": "dash-app",
  "targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/dash",
        "webpackConfig": "apps/dash/webpack.config.js"
      }
    },
    "serve": {
      "executor": "@nx/webpack:dev-server",
      "options": {
        "webpackConfig": "apps/dash/webpack.config.js",
        "proxyConfig": "apps/dash/proxy.conf.json"
      }
    }
  }
}

步骤五:统一管道
nx.json

{
  "tasksRunnerOptions": {
    "default": {
      "runner": "@nx-cloud/nx-cloud",
      "options": {
        "accessToken": "${NX_CLOUD_ACCESS_TOKEN}",
        "cacheableOperations": ["build", "test", "lint"],
        "url": "https://nx-cache.cn-hangzhou.cr.volces.com"
      }
    }
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build", "lint", "test"],
      "inputs": ["production", "^production"]
    }
  },
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)",
      "!{projectRoot}/tsconfig.spec.json",
      "!{projectRoot}/pytest.ini"
    ],
    "sharedGlobals": ["{workspaceRoot}/nx.json", "{workspaceRoot}/pnpm-lock.yaml", "{workspaceRoot}/poetry.lock"]
  }
}

步骤六:本地联调

nx serve fastapi-service &
nx serve dash-app

浏览器访问 http://localhost:4200,Nx 自动把 /api/* 代理到 localhost:8000,Dash 组件可直接调用 FastAPI 接口。

步骤七:CI 增量
.gitlab-ci.yml

stages: [lint, test, build, docker]

variables:
  NX_CLOUD_ACCESS_TOKEN: $NX_CLOUD_TOKEN

lint:
  stage: lint
  image: node:20-alpine
  script:
    - pnpm install --frozen-lockfile
    - pnpm nx affected --base=origin/main --target=lint --parallel=3

test:
  stage: test
  image: python:3.11-slim
  script:
    - pip install poetry
    - poetry install --directory=apps/api
    - pnpm nx affected --base=origin/main --target=test --parallel=3

build:
  stage: build
  image: node:20-alpine
  script:
    - pnpm nx affected --base=origin/main --target=build --parallel=3
  artifacts:
    paths:
      - dist/

docker:
  stage: docker
  image: docker:latest
  services: [docker:dind]
  script:
    - pnpm nx affected --base=origin/main --target=docker-build --parallel=2
    - docker push registry.cn-hangzhou.aliyuncs.com/dp/api:$(pnpm nx show projects --affected --base=origin/main | head -1 | cut -d- -f3)

通过以上配置,Dash+FastAPI 混合仓库即可在 Nx 体系下实现统一命令、增量缓存、双语言依赖隔离与云原生交付,完全满足国内企业对质量、速度、规范的三重要求。

拓展思考

  1. 当 Dash 组件需要 SSR 时,可在 Nx 里新增 @nx/next:app,把 Plotly 图表序列化到服务端,通过 FastAPI 的 jinja2 模板注入首屏数据,进一步提升首屏性能;
  2. 若算法团队使用 Conda 环境,可在 nx.json 中自定义 executor=@nxlv/python:conda-run,把 environment.yml 指纹也纳入缓存键,避免跨平台二进制差异;
  3. 对于多地域部署,可在 Nx Cloud 缓存层前再加一层阿里云 CDN,利用边缘节点把 dist/apps/dash 的静态资源缓存到省会机房,降低 30% 加载延迟;
  4. 安全合规场景下,把 FastAPI 的 requirements.txt 通过 nx 的 posttarget 自动同步到内部 SBOM 平台,实现第三方组件漏洞扫描与许可证治理;
  5. 未来若引入 Rust 高性能模块,只需新增 @nxrs/cargo 插件,继续在同一个 graph 里管理,实现三语言同仓,无需调整现有管道。