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

部署Node.js应用到Vercel遇config包报错:配置属性未定义

问题描述

本地运行Node.js应用时,使用config包管理环境变量完全正常,但部署到Vercel时出现以下错误:

WARNING: NODE_ENV value of 'production' did not match any deployment config file names.
WARNING: No configurations found in configuration directory:/var/task/config
Error: Configuration property "logging.level" is not defined

应用的config目录下存在development.json、production.json和default.json,已尝试设置环境变量NODE_CONFIG_DIR='./config'但问题未解决。

相关配置文件如下:

package.json

{
  "name": "My app",
  "version": "1.0.0",
  "description": "A Application",
  "main": "index.js",
  "engines": {
    "node": "18.x"
  },
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js"
  },
  "author": "hhh",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.0",
    "compression": "^1.7.4",
    "config": "^3.3.8",
    "cors": "^2.8.5",
    "crypto-js": "^4.1.1",
    "express": "^4.18.2",
    "express-async-errors": "^3.1.1",
    "handlebars": "^4.7.7",
    "helmet": "^6.0.0",
    "joi": "^17.7.0",
    "jsonwebtoken": "^8.5.1",
    "lodash": "^4.17.21",
    "mongodb": "^5.3.0",
    "mongoose": "^6.7.3",
    "node-schedule": "^2.1.1",
    "nodemailer": "^6.8.0",
    "socket.io": "^4.6.1",
    "uuid": "^9.0.0",
    "winston": "^3.8.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

./config/default.json

{
  "logging": {
    "level": "info",
    "trace": true
  }
}

应用报错代码:

const config = require("config");
const level = config.get("logging.level"); // ERROR

解决方案

1. 确保config目录被包含在构建产物中

Vercel默认可能不会自动包含所有目录,在package.json中添加files字段,明确指定要打包的目录:

{
  // ...其他原有配置
  "files": [
    "config/",
    "index.js",
    "server/" // 若代码存放在server目录下,需一并添加
  ]
}

2. 修正NODE_CONFIG_DIR的路径

在Vercel环境中,相对路径可能无法正确指向config目录,可通过两种方式修正:

  • 方式一:在Vercel控制台的环境变量设置中,将NODE_CONFIG_DIR设为绝对路径/var/task/config
  • 方式二:在应用入口文件最顶部动态设置路径:
process.env.NODE_CONFIG_DIR = `${process.cwd()}/config`;
const config = require("config");

3. 调整vercel.json配置,强制包含config目录

修改vercel.json,添加includeFiles字段确保config目录被复制到构建环境:

{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node",
      "config": {
        "includeFiles": ["config/**/*"]
      }
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

4. 检查.gitignore配置

确认.gitignore文件未排除config目录,若存在对应规则需删除,否则Vercel拉取代码时无法获取该目录。


内容的提问来源于stack exchange,提问作者ima.technophyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:24:58