Webpack study notes--distinguishing the environment

Source: Internet
Author: User

Why you need to differentiate your environment

In the development of Web pages, there will generally be more than one set of operating environment, such as:

    1. In the development process to facilitate the development of debugging environment.
    2. The run environment that is published to the user on-line.

Although these two sets of different environments are compiled from the same set of source code, the code content is not the same, the differences include:

    • The online code is compressed by the method mentioned in the 4-8 compression code.
    • The code for development contains some hint logs for developers, which are not likely to be viewed by ordinary users.
    • The backend data interface addresses that are connected to the development code may also be different from the online environment, as it is necessary to avoid the impact of the development process on the online data.

In order to reuse the code as much as possible, we need a mechanism to differentiate the environment in the source code, depending on the environment in which the object is to run. Fortunately, Webpack has achieved this for us.

How to differentiate the environment

The specific method of distinguishing is simple, in the source code through the following way:

if (Process.env.NODE_ENV = = = ' Production ') {  console.log (' You are online environment'else  {  Console.log (' You are using the development environment ');}

The approximate principle is to use the value of the environment variable to determine which branch to execute.

When you have a statement in your code that uses the process module, Webpack automatically packs the code into the process module to support a non-node. JS run environment. When you do not use process in your code, you do not package the code into the process module. This injected process module acts to emulate the process in node. js to support the Process.env.NODE_ENV = = = ' production ' statement used above.

When building the online environment code, you need to set the environment variable node_env = ' production ' for the current operating environment, Webpack related configuration is as follows:

Const Defineplugin = require (' webpack/lib/defineplugin '= {  plugins: [    New  Defineplugin ({      //  definition node_env environment variable is production      ' process.env ': {        node_env: Json.stringify (' production ')      }    }),  ],};

Note that the reason for wrapping a string with json.stringify when defining the value of an environment variable is that the value of the environment variable needs to be a string wrapped in double quotation marks, while json.stringify (' production ') The value is exactly equal to "production" .

After the build is executed, you will find the following code in the output file:

if (true) {  console.log (' You are using the online environment 'else  {  console.log (' You are using the development environment ');}

The value of the defined environment variable is substituted into the source code, Process.env.NODE_ENV = = = ' Production ' is replaced directly true . And because the statement that accesses the process at this time is replaced without it, Webpack will not be packaged into the process module.

The environment variables defined by Defineplugin are valid only for the code that Webpack needs to process, without affecting the value of the environment variable at the node. JS Runtime.

environment variables defined by Shell scripting, such as node_env=production Webpack , Webpack are not known, and are not useful for environment-sensitive statements in code that webpack need to process.

In other words, it is necessary to define environment variables by Defineplugin to make the environment-sensitive statements described above work properly, and it is not necessary to define them again through Shell scripts.

If you want Webpack to use the environment variables defined by Shell scripts, you can use Environmentplugin, which is the following code:

New Webpack. Environmentplugin ([' node_env '])

The above code is actually equivalent to:

New Webpack. Defineplugin ({  ' Process.env.NODE_ENV ': json.stringify (Process.env.NODE_ENV),})
Combined with UGLIFYJS

In fact, the above output code can be further optimized, because if(true) statement will always only execute the code in the previous branch, that is, the best output should be directly:

  Console.log (' You are on an online environment ');

Webpack does not implement the removal of dead code functionality, but UGLIFYJS can do this, and how to use it please read the compressed JavaScript in 4-8 compression code.

Environment differentiation in third-party libraries

In addition to the source code can be written in their own environment, many third-party libraries are also optimized for environmental differentiation. Taking React as an example, it makes two sets of environmental distinctions, namely:

    1. Development environment: Contains type checking, HTML element checking, and other warning log codes for developers.
    2. Online Environment: Remove all code for developers, leaving only the parts that make React work, to optimize size and performance.

For example, there is a lot of code like the following in React Source:

if (Process.env.NODE_ENV!== ' production ') {  warning (false, '%s (...): Can only update a mounted or MOU Nting component .... ')}

If you do not define node_env=production then these warning logs will be included in the output code and the output file will be very large.

The node_env and two values in Process.env.NODE_ENV!== ' production ' ‘ production ‘ are conventions of the community, which are typically used to differentiate between the development environment and the online environment. This example provides complete code for the project

Webpack study notes--distinguishing the environment

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.