Knowledge of NODE_ENV in front-end development and its relationship to Webpack

NODE_ENV

The env attribute of the Node.js native process object is an object (MAC environment) :

process.env.NODE_ENV
Copy the code

Obviously, the NODE_ENV attribute is not on the process.env object, but you can see from the literal meaning (Node environment), which means node.js environment.

use

This variable was first used in express.js and then popularized throughout the front-end community.

The main purpose of this property is to distinguish between processing (build, run, etc.) strategies in different environments (development, production, testing, etc.) when executing JavaScript scripts in node.js environments.

Its two most common values are:

process.env.NODE_ENV === 'development'; // or dev for development environment
process.env.NODE_ENV === 'production'; // Or proD for production environment
Copy the code

How to use

In package.json at the root of a front-end project built using NPM, the scripts property is an object, each of which can be run using the NPM run key name on the command line (node.js already installed and commands added to environment variables). The commands that actually run are the keys:

{
  "scripts": {
    "dev": "webpack --config webpack.dev.config.js"}}Copy the code
$ npm run dev
Copy the code

The actual command to run is webpack –config webpack.dev.config.js, and we change the key:

{
  "scripts": {
    "dev": "NODE_ENV=development webpack --config webpack.dev.config.js"}}Copy the code

This injects the NODE_ENV attribute into the process.env object with the value development, Process.env.node_env is only accessible in the webpack.dev.config.js script and the scripts it introduces, not in other scripts.

inwebpackThe use of

Most front-end projects today use Webpack to build single-page applications, where the entry script files reference the rest of the project in a tree structure.

The process.env.node_env attribute provided for the webpack.dev.config.js script is inaccessible to the entry script file handled by Webpack and to the script file referenced by it. However, we can make these scripts accessible to process.env.node_env via webpack plugins:

const webpack = require('webpack');
module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"development"'}})]Copy the code

The last

Thank you for reading, if there are any errors, please correct!