Home  >  Article  >  Web Front-end  >  How to configure the Node project environment to support scalability?

How to configure the Node project environment to support scalability?

青灯夜游
青灯夜游forward
2021-09-29 10:05:032756browse

This article will introduce you to the configuration environment to make the Node project support scalable methods. I hope it will be helpful to everyone!

How to configure the Node project environment to support scalability?

Because there are few Node project developments that do not involve environment variable switching, but you will always encounter it when doing front-end project development. For example, you can configure .env in Vue projects. .xxx.xxx and requires the configuration of environment variables to start with VUE_APP_, Why? , let’s explore together how the environment variables of the Vue project are loaded and parsed, and then we will transplant them to the Node project. [Recommended learning: "nodejs Tutorial"]

Explore the loading of environment configuration in Vue:

Let's take a look firstVue CLI Regarding the description of modes and environment variables, we saw this paragraph: If you want to know the details of the rules for parsing environment files, please refer to dotenv. We also use dotenv-expand to implement variable expansion (Vue CLI 3.5 supports). We first use Vue Cli to create a Vue project.

Explore the first step:

By executing scripts in package.json The commands are all used @vue/cli-service package

How to configure the Node project environment to support scalability?

##Explore the second step:

@vue/cli-service package does install the two dependency packages prompted by the official website, and vue-cli-service in the bin directory. The key class Service was found in the js file.

How to configure the Node project environment to support scalability?

Explore the third step:

  • In

    Service# In ## we found the key function for loading environment configuration, the two path respectively refer to: .env.mode and .env.mode.local , that is, our environment variable file can support .local or not.

  • Think about the role of
  • load

    twice?

How to configure the Node project environment to support scalability?

Explore the third step:

    What happened to the specified prefix? We found the answer in the
  • util

    directory: resolveClientEnv.js, which is ultimately loaded into the global configuration by the DefinePlugin plug-in.

  • Thinking about the settings of
  • BASE_URL

    ?

How to configure the Node project environment to support scalability?

How to configure the Node project environment to support scalability?

Add environment configuration to the Node project carrying webpack

Prepare webpack project environment

Prepare webpack.config.js

How to configure the Node project environment to support scalability?

Add env-helper.js, let’s implement it together:

Install the necessary dependencies

npm install dotenv --save
npm install dotenv-expand --save

Parsing environment variable files

/**
 * 解析环境变量文件
 * @param {*} mode
 */
const loadEnv = (mode) => {
  const basePath = path.resolve(__dirname, `.env${mode ? `.${mode}` : ``}`);
  const localPath = `${basePath}.local`;

  const load = (envPath) => {
    try {
      const env = dotenv.config({ path: envPath, debug: process.env.DEBUG });
      dotenvExpand(env);
    } catch (err) {
      if (err.toString().indexOf("ENOENT") < 0) {
        console.error(err);
      }
    }
  };

  load(localPath);
  load(basePath);
};

Environment variable objects that match the prefix

After integrating the regular conditions and special ones Return, by injecting into the
DefinePlugin

plugin.

/**
 * 获取符合前缀规则的环境变量对象
 */
const prefixRE = /^XXTX_APP_/;
const resolveClientEnv = () => {
  const env = {};
  Object.keys(process.env).forEach((key) => {
    if (prefixRE.test(key) || key === "NODE_ENV") {
      env[key] = process.env[key];
    }
  });
  return env;
};

Upgrade webpack.config.js to demonstrate environment variable reading

Add demonstration plug-in and NODE_ENV configuration

const webpack = require("webpack");
const { loadEnv, resolveClientEnv } = require("./env-helper");
// 解析环境配置文件
// 通过cross-env 再scripts中配置NODE_ENV=development
loadEnv(process.env.NODE_ENV);
// 获取符合规则的环境配置对象
const env = resolveClientEnv();

const HelloWorldPlugin = require("./hello-world");

module.exports = {
  mode: "development",
  plugins: [
    new webpack.DefinePlugin(env),
    new HelloWorldPlugin({ options: true }),
  ],
};

Use environment variables in our webpack plugin

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.done.tap("HelloWorldPlugin", () => {
      console.log("Hello World!");
      console.log("[ XXTX_APP_NAME ] >", process.env.XXTX_APP_NAME);
      console.log("[ XXTX_APP_BASE_URL ] >", process.env.XXTX_APP_BASE_URL);
    });
  }
}

module.exports = HelloWorldPlugin;

View the output

How to configure the Node project environment to support scalability?

Ending note:

    We can transplant
  • env-helper.js

    to other NodeOnly the way to mount the configuration can be changed in the project.

  • This time the code relies entirely on the CV method. Have you learned it?

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to configure the Node project environment to support scalability?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete