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

Vue项目GitLab CI/CD中Nightwatch环境变量未定义问题求助

Fixing "ReferenceError: NIGHTWATCH_CONFIG is not defined" in Nightwatch + GitLab CI Setup

Let's break down what's going wrong here and fix it step by step.

The Root Cause

The error pops up because you’re trying to access NIGHTWATCH_CONFIG as a top-level variable, but in Node.js, all environment variables live under the process.env object. When you set process.env.NIGHTWATCH_CONFIG in your runner files, you can’t reference it directly by name—you have to pull it from the process.env object explicitly.

Step 1: Fix the Variable Reference in runner.js

Update your runner.js code to use process.env.NIGHTWATCH_CONFIG instead of the bare variable name. It’s also smart to add a fallback value, so if the environment variable isn’t set for some reason, your script doesn’t break unexpectedly:

// runner.js
// ... existing code ...
const configFileName = process.env.NIGHTWATCH_CONFIG || 'nightwatch.conf.js'; // Add fallback for safety
opts = opts.concat(['--config', `test/e2e/${configFileName}`]);
// ... rest of your code ...

Step 2: Verify Environment Variable Propagation

Your local_runner.js and gitlab_runner.js files are correctly setting the environment variable before requiring runner.js, so that part should work now that you’re accessing the variable via process.env.

To double-check, you can add a quick console log at the top of runner.js to confirm the variable is being passed correctly:

console.log('Loaded Nightwatch config:', process.env.NIGHTWATCH_CONFIG);

Optional: Simplify Your Setup (Ditch Extra Runner Files)

If you want to clean up your codebase, you can eliminate the separate local_runner.js and gitlab_runner.js files by setting the environment variable directly in your package.json scripts. Use the cross-env package to make this work seamlessly across Windows, macOS, and Linux:

  1. First install cross-env as a dev dependency:
npm install --save-dev cross-env
  1. Update your package.json scripts:
"scripts": {
  "e2e": "cross-env NIGHTWATCH_CONFIG=nightwatch.conf.js node test/e2e/runner.js",
  "local-test": "cross-env NIGHTWATCH_CONFIG=nightwatch.local.js node test/e2e/runner.js",
  "test": "npm run e2e"
}

This approach cuts out the intermediate runner files entirely—you’re setting the environment variable directly when invoking the script, making your setup cleaner and more maintainable.

Test the Fix

Run your local test script first to confirm the error is resolved:

npm run local-test

Then trigger your GitLab CI pipeline to ensure the CI-specific config loads correctly without issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:13:02