Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...