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

如何为Next.js(v14.0.3)传递自定义命令行参数?

Next.js 14.0.3 传递自定义命令行参数的正规方案

1. 正确使用 -- 分隔自定义参数

Next.js 支持用 -- 分隔框架自带参数和你的自定义参数,之前报错大概率是参数位置不对。

开发环境(next dev)

命令格式:

next dev -- --custom-arg1 value1 --custom-arg2 value2

示例:

next dev -- --build-mode staging --feature-flag enable-dark-mode

构建环境(next build)

命令格式:

next build -- --custom-arg1 value1 --custom-arg2 value2

示例:

next build -- --env production --bundle-analyzer

2. 在代码中获取自定义参数

服务端/next.config.js 中获取

直接通过 process.argv 解析,可写个简单的解析函数处理:

// next.config.js
function getCustomArgs() {
  const args = process.argv.slice(2);
  const customArgsStartIndex = args.indexOf('--');
  if (customArgsStartIndex === -1) return {};
  
  const customArgs = args.slice(customArgsStartIndex + 1);
  const result = {};
  
  for (let i = 0; i < customArgs.length; i++) {
    const arg = customArgs[i];
    if (arg.startsWith('--')) {
      const key = arg.slice(2);
      const value = customArgs[i + 1]?.startsWith('--') ? true : customArgs[i + 1];
      result[key] = value;
      if (value !== true) i++;
    }
  }
  return result;
}

const customArgs = getCustomArgs();

/** @type {import('next').NextConfig} */
const nextConfig = {
  env: {
    BUILD_MODE: customArgs['build-mode'] || 'development',
  },
  webpack: (config, { isServer }) => {
    // 根据参数开启打包分析
    if (customArgs['bundle-analyzer']) {
      const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
      config.plugins.push(new BundleAnalyzerPlugin());
    }
    return config;
  },
};

module.exports = nextConfig;

客户端组件中获取

如果需要在客户端访问参数,有两种方式:

  • 用 NEXT_PUBLIC_ 前缀的环境变量,直接在命令行设置:
    NEXT_PUBLIC_BUILD_MODE=staging next dev
    
    之后在客户端组件中直接通过 process.env.NEXT_PUBLIC_BUILD_MODE 获取。
  • 在服务端组件中解析自定义参数,通过 props 传递给客户端组件。

3. 简洁替代:直接设置环境变量

如果不需要复杂的参数结构,直接在命令行设置环境变量更省心:

# 仅服务端可用的环境变量
BUILD_MODE=staging next dev
# 客户端也能访问的环境变量(需加NEXT_PUBLIC_前缀)
NEXT_PUBLIC_FEATURE_FLAG=enable next build

这种方式无需解析 process.argv,直接通过 process.env 读取即可。

注意事项

  • 自定义参数必须放在 -- 之后,否则会被Next.js识别为框架自身参数,导致报错。
  • 客户端组件无法直接读取 process.argv,只能通过 NEXT_PUBLIC_ 前缀环境变量或服务端组件传参的方式获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:43:19