Implementation of conditional compilation in JavaScript (JS conditional compile loader plug-in based on webpack)

Time:2020-2-1

Conditional compilation refers to the process of selectively compiling the specified code according to the set conditions with the same set of code and the same compilation and construction process, so as to output different programs. Generally used in C + +, Java, C ා, and other compiled execution languages. For JavaScript, we can also use thewebpackOfjs-conditional-compile-loaderThe plug-in implements similar conditional compilation functions.

Examples of application scenarios

We often encounter such needs:

  • Code needs to be based onRunning environmentRunDifferent codes。 For example, the test environment can output some information from the console, while the production environment does not prompt; at the same time, it is not expected that the output code contains the if else code that judges the environment to increase the package volume.
  • Project delivery toMultiple clientsUse, and some customers will have someCustom module。 These customized modules are only used by specific users, and they do not want to be packaged in the packages of unrelated customers together, but also do not want to increase the maintenance cost by maintaining a special project for customized customers.
  • The front end references a lot of mock data for debugging. But the production environment also includes these mock data and mock plug-ins when packaging, which increases the code package volume. You want the production environment package to be completely free of these (even if it’s loaded asynchronously on demand).

Using the method of conditional compilation, this problem can be solved gracefully. At the same time, the code is easy to maintain, and there will be no redundant code in the published package.

Plug in principle

JS conditional compile loader plug-in is a webpack loader plug-in. It will modify the JS code according to the set conditions before webpack processes the JS code, remove the unnecessary code under the current conditions, and retain the required code, so as to realize the function of conditional compilation.

Using steps

Please refer to the Chinese documents here.

1. installation

npm i -D js-conditional-compile-loader

2. Configure webpack

Add a loader to the JS file in rules as the first step to process the JS file and configure the compilation conditions.

module: {
    rules: [
        {
            test: /\.js$/,
            include: [resolve('src'), resolve('test')],
            use: [
                //step-2
                'babel-loader?cacheDirectory',
                //step-1
                {
                    loader: 'js-conditional-compile-loader',
                    options: {
                        isDebug: process.env.NODE_ENV === 'development', // optional, this is default
                        myFlag: process.env.npm_config_ali, // any name, used for /* IFTRUE_myFlag ...js code... FITRUE_myFlag */
                    }
                },
            ]
        },
        //other rules
    ]
}

3. Used in project code

The plug-in supports ifdebug and iftrue conditional compilation instructions. Usage: anywhere in JS code/*IFDEBUGor/*IFTRUE_xxxBegin withFIDEBUG*/orFITRUE_xxx*/At the end, the wrapped JS code is in the middle. XXX is the condition property name specified in webpack, such as myFlag above.

for instance,

Source code:

We use this source code:

/* IFTRUE_forAlibaba */
var aliCode = require('./ali/alibaba-business.js')
aliCode.doSomething()
/* FITRUE_forAlibaba */

$state.go('win', {dir: menu.winId /*IFDEBUG , reload: true FIDEBUG*/})

Condition 1 output

When the options of plug-ins in webpack are configured as{isDebug: true, forAlibaba: true}The output after construction:

var aliCode = require('./ali/alibaba-business.js')
aliCode.doSomething()

$state.go('win', {dir: menu.winId, reload: true })

Condition 2 output

When the options of plug-ins in webpack are configured as{isDebug: false, forAlibaba: false}After construction, the output is:

$state.go('win', {dir: menu.winId})

This enables conditional compilation. Combining command parameters with environment variables, you can use command parameters to specify different compilation conditions. For example, the configuration conditions in this article:myFlag: process.env.npm_config_ali, with--aliCan be activated astruenpm run build --ali
In the actual project, you can give full play to your needs.

Example project

Here is an example of a complete project for reference.

Recommended Today

Blog based on beego, go blog

Go Blog A beego based development, can quickly create personal blog, CMS system Include functions see Official website of go bloggo-blog.cn Demo siteleechan.online Update log time function January 23, 2020 New top post function February 2, 2020 New custom navigation function February 4, 2020 New site announcement function February 6, 2020 New link module February […]