Nuxt how to distinguish between different environments

Time:2021-10-21

background

In general, our project must distinguish different environments to determine the corresponding strategies, including but not limited to interface forwarding address, packaging strategy, log output strategy, etc. Then, regardless of the specific content to be set, we need to have the ability to distinguish the environment before we can do these things. So does nuxt provide us with such basic capabilities? The answer is yes.

Let’s take the forwarding address of the interface that will certainly be different in different environments as an example to illustrate.

nuxt.config.js

Students who develop with nuxt framework believe that they are not unfamiliar with this configuration file, so this paper will also involve a specific configuration, that is, the configuration of Axios. The configured address depends on a variable, which is uncertain. The configuration code is as follows:

Note: please refer to my other articles on how to configure Axios and proxy.

export default {
 modules: ["@nuxtjs/axios"],
 axios: {
        //Allow cross domain
        proxy: true,
        //Up to three retransmissions
        retry: {
            retries: 3,
        },
        //Open debug in non online environment
        debug: !isProd,
        //Is it trusted
        withCredentials: true,
        timeout: 2000,
    },
proxy: {
        "/api": {
            changeOrigin: true,
            target: targetUrl,
            pathRewrite: {
                "^/api": "/api",
            },
        }
   }
}

key parameter

isProd , targetUrl

The addresses of different environments can be maintained statically, and the corresponding environment addresses can be obtained according to the environment ID. whether it is a production environment can also be controlled through the environment ID.
Suppose that the configuration dictionaries of our different environments are like this (it is recommended to write a separate config. JS configuration file).
Note: except that the domain name configuration is different between the advance environment and the production environment, the others should be consistent as far as possible, and strange problems can be solved as far as possible.


export default {
    dev: "http://dev.xxx.net/",
    stable: "https://stable.xxx.net/",
    pre: "https://pre.xxx.com/",
    prod: "http://xxx.com/",
}

Then the use of defined variables is as follows:


const isProd = process.env.NODE_ENV === "prod";
const targetUrl = serverConfig[ process.env.NODE_ENV || 'stable'];

Then process.env.node_ How is env defined? We handle it differently according to different stages of project development.
Development phase setting variables

There is an open source library in NPM, which can set node variables across platforms. It is cross Env, NPM module address: https://www.npmjs.com/package/cross-env , I won’t repeat how to install it.

Because local development generally executes NPM run dev, and the default execution command of the package file does not distinguish the configuration of the environment, we can directly add the corresponding executable script to the executable script of the package file. The purpose is that I don’t want to constantly modify my configuration file or select which file to modify through comments in order to switch the environment, In addition, this is more in line with development habits. In general, we will not switch and debug a function back and forth in various environments.

Executable command appended in package.json: node defined by us_ Env value is our key value in the configuration file. Please keep them consistent.


 "scripts": {
    "dev": "cross-env NODE_ENV=dev nuxt",
    "dev-stable": "cross-env NODE_ENV=stable nuxt",
    "dev-pre": "cross-env NODE_ENV=pre nuxt",
    "dev-prod": "cross-env NODE_ENV=prod nuxt"
 }

Deployment phase

In the deployment phase, as common sense, we know that the final deployment must be the deployment of the server process daemon, not NPM run start. Therefore, the corresponding introduction of PM2 is a basic selection, and the PM2 ecology supports deployment using configuration files. You can create ecosystem.config.js in the root directory, and then configure the basic contents as follows: env_ XX is the part that supports the configuration of environment variables in PM2. Compared with cross Env, the way of setting variables is more concise, which is a JS basic object format. Keep node set_ Env and corresponding env identification.


module.exports = {
  apps: [
    {
      name: 'demo_pc',
      exec_mode: 'cluster',
      instances: '2', // Or a number of instances
      script: './node_modules/nuxt/bin/nuxt.js',
      args: 'start',
      log_date_format:'hxpc_YYYY-MM-DD HH:mm Z',
      log_file:'pc.log',
      out_file: 'out.log',
      env: {
        "NODE_ENV": "prod",
      },
      env_dev: {
        "NODE_ENV": "dev",
      },
      env_prod : {
         "NODE_ENV": "prod"
      },
      env_pre : {
        "NODE_ENV": "pre"
      },
      env_stable : {
        "NODE_ENV": "stable"
     }
    },
   ]
 }

Then, at startup, you can use PM2 start — env stable to specify which environment to use. In order to facilitate operation and maintenance, I customarily set the default env to start the production environment configuration. PM2 start. In this case, the corresponding configuration of Env will be used.

Summary

That’s all for this article. I hope you can clearly know how to customize settings and use some environment difference variables according to environment identification, and explore and make good use of this.

This is the end of this article on how to distinguish between different environments of nuxt. For more information about how to distinguish between different environments of nuxt, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]