Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Environment variable switch is not involved in Node project development, but often front-end project development is always encountered, such as in Vue project can be configured. Env.xxx. XXX and require the configuration of environment variable to start with VUE_APP_, Why? Let’s explore how Vue project environment variables are loaded and parsed before porting them to Node projects.

Explore loading environment configuration in Vue:

Taking a look at the Vue CLI’s instructions on schemas and environment variables, we see this: For details on parsing environment file rules, refer to Dotenv. We also use Dotenv-expand for variable expansion (Vue CLI 3.5+ support). Let’s start by creating a Vue project using the Vue Cli.

First step of exploration:

inpackage.jsonThrough the execution ofscriptsThe command is used@vue/cli-servicepackage

Explore the second step:

@vue/cli-serviceThe package does install the two dependency packages suggested on the official website, and thebinIn the directoryvue-cli-service.jsKey classes are found in the fileService.

Step 3:

  1. inServiceWe found two of the key functions for loading the environment configurationpathRespectively refers to:.env.modeand.env.mode.local, that is, our environment variable files can support belt.localOr you don’t have to.
  2. thinkingloadWhat’s twice worth?

Step 3:

  1. What about the specified prefix? We are inutilThe answer was found in the directory:resolveClientEnv.jsFinally, byDefinePluginThe plug-in is loaded into the global configuration.
  2. thinkingBASE_URLThe Settings?

Add environment configuration to the Node project with WebPack

Prepare the Webpack project environment

Prepare webpack. Config. Js

Env-helper. js (env-helper.js)

Must rely on fake

npm install dotenv --save
npm install dotenv-expand --save
Copy the code

Parse the environment variable file

/** * Parse the environment variable file *@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); };Copy the code

The environment variable object that matches the prefix

The reged-qualified and special ones are returned by consolidation and injected into DefinePlugin.

/** * gets the environment variable object */ that matches the prefix rule
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;
};
Copy the code

Upgrade webpack.config.js to demonstrate environment variable reading

Add demo plug-ins and NODE_ENV configuration

const webpack = require("webpack");
const { loadEnv, resolveClientEnv } = require("./env-helper");
// Parse the environment configuration file
// use cross-env to configure NODE_ENV=development in scripts
loadEnv(process.env.NODE_ENV);
// Get the environment configuration object that meets the rule
const env = resolveClientEnv();

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

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

Use environment variables in our Webpack plug-in

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;
Copy the code

Viewing the output

Closing note:

  1. We can putenv-helper.jsTransplant to something elseNodeJust change the way the configuration is mounted in the project.
  2. This code all depends on CV big method, have you learned?

My name is Xiaoxin.

  • 😇 Familiar with: Android development, front-end development.
  • 🤪 Understand: back-end development, script development.
  • 🧐 specialty: solve difficult and miscellaneous diseases in coding.
  • 😇 motto: a thousand miles, small streams to become rivers and oceans.