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.json
Through the execution ofscripts
The command is used@vue/cli-service
package
Explore the second step:
@vue/cli-service
The package does install the two dependency packages suggested on the official website, and thebin
In the directoryvue-cli-service.js
Key classes are found in the fileService
.
Step 3:
- in
Service
We found two of the key functions for loading the environment configurationpath
Respectively refers to:.env.mode
and.env.mode.local
, that is, our environment variable files can support belt.local
Or you don’t have to. - thinking
load
What’s twice worth?
Step 3:
- What about the specified prefix? We are in
util
The answer was found in the directory:resolveClientEnv.js
Finally, byDefinePlugin
The plug-in is loaded into the global configuration. - thinking
BASE_URL
The 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:
- We can put
env-helper.js
Transplant to something elseNode
Just change the way the configuration is mounted in the project. - 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.