'Remove some code lines in production distribution files?

I'm using Babel and Webpack to generate ES5 code from ES6. There are some validations that is used to reduce the mistakes i do while coding.

class Logger {
    /**
     * @param {LogModel} info
     *  {LogTypes} type
     *  {String} message
     *  {Date} date
     */
    static log(info) {
        if(info instanceof LogModel)
            throw new Error("not a instance of LogModel");

        notify(info);
    }
}

In log function, I validate whether the argument is a instance of LogModel class. This is just to prevent mistakes. I don't want that if condition to be in the production because too many if condition going to slow the application. Is it possible to generate development release with validations and production release without those validations with Babel and Webpack?



Solution 1:[1]

It appears the other answers are outdated. With webpack 4, you can set mode: 'production' in your webpack config.

In your code, check for development mode like this:

if (process.env.NODE_ENV === 'development') {
    if(info instanceof LogModel)
        throw new Error("not a instance of LogModel");
}

When webpack creates a bundle with mode: 'production', all the code inside these if clauses, along with the if clauses themselves, will be automatically removed from the bundle.

There is no need to use the define plugin explicitly (it is used by webpack “under the hood”), and it's not necessary to use something like webpack-unassert-loader or webpack-strip-block mentioned in other answers.

Check out this little demo repo I have made to try this out: https://github.com/pahund/webpack-devprod-experiment

Solution 2:[2]

webpack-strip-block is a good solution. It removes a block of code in your production code when compiling.

/* develblock:start */
/* develblock:end */

Not limited to asserts and no redundant code in prod.

Solution 3:[3]

A cleaner option will be using define-plugin from webpack.

In config file:

new webpack.DefinePlugin({ __DEV: JSON.stringify(true) })

app.js:

if(__DEV){ console.log("logged only in dev env") }

value of __DEV will be provided by webpack at compile time.

Solution 4:[4]

You can use the assert package to enforce your code, then use webpack-unassert-loader or webpack-strip-assert to strip your assertions for production code.

var assert = require('assert').ok;

class Logger {
    /**
     * @param {LogModel} info
     *  {LogTypes} type
     *  {String} message
     *  {Date} date
     */
    static log(info) {
        assert(info instanceof LogModel, "Param must be an instance of LogModel");
        notify(info);
    }
}

Solution 5:[5]

I created a sample project to evaluate all the different approaches explain in this thread. My favorite is to use string-replace-webpack-plugin.

Solution 6:[6]

There are some great options here, but I think we can do better. If you're trying to completely remove the Logger.log() function as well as calls to it like:

Logger.log('Remove me');

...then string-replace-loader can do what we need!

Install string-replace-loader:

npm install --save-dev string-replace-loader

Then, in your Webpack config:

...
    module: {
        rules: [
            //Replace strings
            {
                test: /\.js$/,
                loader: 'string-replace-loader',
                options: {
                    multiple: [
                        //Remove calls to Logger.log()
                        {
                            search: /Logger\.log\s*\(.*?\);?\s*?\n/g,
                            replace: '\n'
                        },
                        //Remove the actual Logger.log() function. This regex may need tweaking depending on your actual code for `log()`.
                        {
                            search: /static\s*log\s*\([^}]*}/gs,
                            replace: ''
                        }
                    ]
                }
            }
        ]
    },
...

No need to add extra meaningless code to the actual source code. Enjoy!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 s1n7ax
Solution 3 Arjun
Solution 4 rgthree
Solution 5 geri-m
Solution 6