如何将命令行参数传递给 vue.config.js?

How to pass command-line arguments to vue.config.js?

我正在尝试配置一个 vue 项目,以便 webpack-dev-server 将对 /data 的请求代理到两个主机之一,具体取决于调用哪个 npm-运行 命令:

npm run serve-foo
npm run serve-bar

配置如下:

// package.json
{
  scripts: {
    'serve-foo': 'vue-cli-service serve -- http://192.168.7.2',
    'serve-bar': 'vue-cli-service serve -- http://192.168.7.3',
}

// vue.config.js

// prints "node.exe vue-cli-service.js serve -- http://192.168.7.2"
console.log(...process.argv); 

module.exports = {
  devServer: {
    // ...
    proxy: {
      '/data': {
        target: process.argv[4]
      }
    }
  }
}

现在当我运行 npm 运行 serve-foo 时出现以下错误。 我做错了什么? vue-cli-service 不支持使用 -- 传递参数吗?

This dependency was not found:

C:\Project\http:2.168.7.2 in multi (webpack)-dev-server/client?http://192.168.0.5:80/sockjs-node (webpack)/hot/dev-server.js ./http:/192.168.7.2, multi (webpack)-dev-server/client?http://localhost:80 (webpack)/hot/dev-server.js (webpack)-dev-server/client?http://192.168.0.5:80/sockjs-node ./http:/192.168.7.2
To install it, you can run: npm install --save C:\Project\http:2.168.7.2

您可以通过环境变量实现:

// package.json
{
  scripts: {
    'serve-foo': 'export BACKEND_URL=http://192.168.7.2 && vue-cli-service serve',
    'serve-bar': 'export BACKEND_URL=http://192.168.7.3 && vue-cli-service serve',
}

// vue.config.js    
module.exports = {
  devServer: {
    // ...
    proxy: {
      '/data': {
        target: process.env.BACKEND_URL
      }
    }
  }
}