构建暂存环境时如何忽略 vue.config.js 中的 devServer 设置?

How to ignore devServer settings in vue.config.js when building for staging environment?

我正在使用 Vue 构建一个应用程序。为了开发和测试目的,我需要 https 在我的本地环境中工作。我成功创建了必要的证书 following this tutorial。为了让开发服务器使用它们,我将 server.keyserver.crt 文件复制到项目的根目录中,并将 rootCA.pem 文件留在 ~/.ssh 中。我在 /etc/hosts 中为我的域添加了一个别名 localhost 条目,例如:

127.0.0.1 example.test

然后我在项目的根目录中编辑 vue.config.js 如下所示:

const fs = require('fs')

module.exports = {
  devServer: {
    host: 'example.test',
    https: {
      key: fs.readFileSync('./server.key'),
      cert: fs.readFileSync('./server.crt'),
      ca: fs.readFileSync(process.env.HOME + '/.ssh/rootCA.pem')
    }
  }
}

这在本地很好。我的问题出在我的暂存服务器上。

我的登台服务器是 运行 ubuntu (16.04) 并且使用 certbot (LetsEncrypt) 安装了实际的 SSL 证书(即非自签名)。我的项目是一个静态前端,所以我将 nginx 配置为指向 /dist 目录并使项目在 staging.example.com 可用。在我在上面的 vue.config.js 中添加 devServer 配置之前,一切正常。

期望发生的事情:

当我构建用于暂存的项目时,即

npm run build -- --mode staging

我预计它会忽略 devServer 配置部分,因为 NODE_ENV === 'production'(在我的 .env.staging 文件中设置)。

实际上发生了什么:

构建过程失败,抱怨:

Error loading vue.config.js:
Error: ENOENT: no such file or directory, open './server.key'

问题:如何让构建过程在为 "staging" 或 "production?"

构建时忽略 vue.config.jsdevServer 部分

vue.config.js 不会自动检测环境。作为 it says in the Vue CLI configuration docs:

If you need conditional behavior based on the environment, or want to directly mutate the config, use a function (which will be lazy evaluated after the env variables are set). The function receives the resolved config as the argument. Inside the function, you can either mutate the config directly, OR return an object which will be merged.

我不是很清楚如何实际执行此操作。这是最终起作用的:

const fs = require('fs')

module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV !== 'production') {
      config.devServer = {
        host: 'qzuku.test',
        // https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec
        https: {
          key: fs.readFileSync('./qzukuDevServer.key'),
          cert: fs.readFileSync('./qzukuDevServer.crt'),
          ca: fs.readFileSync(process.env.HOME + '/.ssh/rootDevCA.pem')
        }
      }
    }
  }
}

希望对您有所帮助!