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

时间:2020-04-20 01:41:41

标签: vue.js webpack webpack-dev-server

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

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 run serve-foo时,会发生以下错误。 我在做什么错了? vue-cli-service不支持使用--来传递参数吗?

This dependency was not found:

C:\Project\http:\192.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:\192.168.7.2

1 个答案:

答案 0 :(得分:1)

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

// 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
      }
    }
  }
}