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

DigitalOcean Node.js Serverless函数部署后依赖包找不到问题排查

DigitalOcean Serverless函数依赖找不到问题的修复方案

核心问题分析

本地运行正常但部署后出现ERR_MODULE_NOT_FOUND,本质是部署流程中依赖未正确安装、文件结构混乱或模块解析不兼容导致的。以下是针对性的修复步骤:

1. 强制部署时安装生产依赖并执行构建

DigitalOcean Serverless默认的构建逻辑可能未正确触发自定义脚本,导致依赖缺失。

  • 修改package.json的构建脚本,明确安装生产依赖:
    "scripts": {
      "build": "tsc",
      "build:digitalocean": "npm install --production && npm run build"
    }
    
  • 在project.yml中添加构建命令配置,确保DO执行指定脚本:
    packages:
      - name: documents
        build_command: "npm run build:digitalocean"
        # 保留原有其他配置...
        functions:
          # 保留原有函数配置...
    

2. 修正TypeScript编译路径避免文件混乱

当前tsconfig.json的outDir和rootDir都设为根目录,编译后的JS文件与TS源码混杂,会干扰部署时的依赖解析。

  • 调整TS配置,将编译产物输出到单独目录:
    {
      "compilerOptions": {
        "target": "ES2021",
        "module": "ES2022",
        "sourceMap": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "outDir": "./dist", // 输出到dist目录
        "rootDir": "./src"  // 假设TS源码在src目录,根据实际调整
      },
      "include": ["src/**/*.ts"],
      "exclude": ["node_modules", "dist"]
    }
    
  • 更新入口文件路径:
    • package.json中修改main字段:"main": "dist/index.js"
    • project.yml中函数的main字段改为:main: 'dist/index.js'

3. 确保ES模块导入路径正确

使用"type": "module"时,ES模块要求导入文件必须带完整扩展名,否则部署后会出现解析错误。

  • 检查所有TS导入语句,确保添加.js扩展名(TypeScript编译时会自动处理,但源码中需正确书写):
    // 错误示例
    import { helper } from './utils'
    // 正确示例
    import { helper } from './utils.js'
    

4. 适配原生模块(如sharp)的构建环境

sharp这类依赖原生二进制的模块,需要在构建时指定与DO Serverless匹配的平台(Linux x64):

  • 修改build:digitalocean脚本,添加sharp平台参数:
    "build:digitalocean": "npm install --production --sharp-platform=linux --sharp-arch=x64 && npm run build"
    

验证流程

  1. 本地执行npm run build:digitalocean,确认dist目录生成正确的JS文件,node_modules包含所有生产依赖。
  2. 用doctl serverless deploy .重新部署,观察部署日志无报错。
  3. 调用函数测试依赖加载是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:03:27