问题:如何在生产环境禁止 console log ??
开发和测试环境中会用到大量 console.log 方法来进行代码的调试,但生产上需要关闭这些输出。
因为 console.log 打印的对象是不会被垃圾回收器回收的,这样可能会影响页面的整体性能,尤其是在开发环境可能会引起一起不必要的 bug
有以下两种方法:
Hack 方法
- 这应该是最容易想到的方法,直接改写 console.log 的方法。
- 在生产环境禁止打印的方法 (Node 环境下,我本人的项目是 react)
1 2 3 4 5 6 7
|
console.log("Env:%o,:%o", process.env.NODE_ENV); if (process.env.NODE_ENV === "production") { console = console || {}; console.log = function () {}; }
|
webpack 构件工具中配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); plugins: [ new UglifyJsPlugin({ uglifyOptions: { compress: { drop_console: true, }, }, }), ];
plugins: [ new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false, drop_debugger: true, drop_console: true, }, }, }), ];
|
更多更好用的方法,请在下方评论告知谢谢 🙂