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

使用Vue-cli V3时,能否访问系统环境变量替代.env文件?

Hey there! Great question—yes, you absolutely can access local system environment variables with Vue CLI 3, even when you can't use .env files because of your Jenkins build workflow constraints. Let me walk you through how to make this work for your test mode flag:

Inject system env vars via vue.config.js

Vue CLI lets you tap into Node.js's process.env object (which includes all system environment variables available to the Node process) and inject them into your frontend code using Webpack's DefinePlugin. Here's a concrete example:

// vue.config.js
const { defineConfig } = require('@vue/cli-service');
const webpack = require('webpack');

module.exports = defineConfig({
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        // Replace YOUR_SYSTEM_TEST_VAR with your actual system env variable name
        'process.env.IS_TEST_MODE': JSON.stringify(process.env.YOUR_SYSTEM_TEST_VAR)
      })
    ]
  }
});

Once this is set up, you can directly use process.env.IS_TEST_MODE in your Vue components to check if you're in test mode. Just make sure the system environment variable is set before you run your Vue CLI build/serve commands.

Pass env vars directly in build commands (for Jenkins flexibility)

If you need to set the test mode flag dynamically during your Jenkins build (instead of relying on a pre-existing system variable), you can pass it directly in your npm script. For example:

In your package.json:

{
  "scripts": {
    "build": "vue-cli-service build",
    "build:test": "IS_TEST_MODE=true vue-cli-service build"
  }
}

Then in Jenkins, you just run npm run build:test instead of the regular build command, and the IS_TEST_MODE variable will be available in your vue.config.js via process.env.IS_TEST_MODE.

Key things to remember

  • Make sure the system environment variable is available to the Node.js process that runs Vue CLI. On Linux/macOS, this means exporting it before running your command (e.g., export YOUR_SYSTEM_TEST_VAR=true && npm run build). On Windows, use set YOUR_SYSTEM_TEST_VAR=true && npm run build.
  • Always use JSON.stringify() when injecting variables via DefinePlugin—this ensures strings are properly quoted, and booleans/numbers are parsed correctly in the frontend.
  • System environment variables are case-sensitive on Linux/macOS, but not on Windows. Keep this in mind if your build pipeline runs across different OSes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:53:30