我正在使用 Babel
和 Webpack
从 ES6
生成 ES5
代码。有一些验证可用于减少我在编码时犯的错误。
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);
}
}
在 log
函数中,我验证参数是否是 LogModel
类的实例。这只是为了防止错误。我不希望 if 条件出现在生产中,因为太多 if 条件会减慢应用程序的速度。是否可以通过 Babel
和 Webpack
生成带验证的开发版本和不带验证的生产版本?
最佳答案
看来其他答案已经过时了。使用 webpack 4,您可以在 webpack 配置中设置 mode: 'production'
。
在您的代码中,像这样检查开发模式:
if (process.env.NODE_ENV === 'development') {
if(info instanceof LogModel)
throw new Error("not a instance of LogModel");
}
当 webpack 使用 mode: 'production'
创建 bundle 时,这些 if 子句中的所有代码以及 if 子句本身都会自动从 bundle 中删除。
不需要显式使用 define 插件(它被 webpack “在幕后”使用),也不需要使用像 webpack-unassert-loader
或 这样的东西webpack-strip-block
在其他答案中提到。
查看我制作的这个小演示库来尝试一下:https://github.com/pahund/webpack-devprod-experiment
关于javascript - 删除生产分发文件中的一些代码行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45776264/