如何在开发(开启)生产(禁用)console.log调试信息呢?

1,196 阅读2分钟

为了安全和规范,开发调试内容发布到生产环境往往不允许出现console;那如果是团队开发成百上千的console总不能一个个删吧? 那如果系统可以自动判断,开发环境输出console生产环境禁用console。这样既不耽误调试也不影响代码安全!!!

花里胡哨的console表面上五颜六色,实际上用户也看不到但是好看啊。就像这样

1.png

新建 /utils/log/console.js

// 美化打印实现方法
const prettyLog = () => {
    // const isProduction = 'production';
    const isProduction = process.env.NODE_ENV === 'production';//如果获取不到就注释本行,打开上面一行注释
    console.log('环境是==',isProduction);
    const isEmpty = (value) => {
        return value == null || value === undefined || value === '';
    };
    const prettyPrint = (title, text, color) => {
        // 如果是生成环境 prettyLog不打印任何log信息
        if (isProduction) return;
        console.log(
            `%c ${title} %c ${text} %c`,
            `background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
            `border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
            'background:transparent'
        );
    };
    const info = (textOrTitle, content = '') => {
        const title = isEmpty(content) ? 'Info' : textOrTitle;
        const text = isEmpty(content) ? textOrTitle : content;
        prettyPrint(title, text, '#909399');
    };
    const error = (textOrTitle, content = '') => {
        const title = isEmpty(content) ? 'Error' : textOrTitle;
        const text = isEmpty(content) ? textOrTitle : content;
        prettyPrint(title, text, '#F56C6C');
    };
    const warning = (textOrTitle, content = '') => {
        const title = isEmpty(content) ? 'Warning' : textOrTitle;
        const text = isEmpty(content) ? textOrTitle : content;
        prettyPrint(title, text, '#E6A23C');
    };
    const success = (textOrTitle, content = '') => {
        const title = isEmpty(content) ? 'Success ' : textOrTitle;
        const text = isEmpty(content) ? textOrTitle : content;
        prettyPrint(title, text, '#67C23A');
    };
    const table = () => {
        const data = [
            { id: 1, name: 'Alice', age: 25 },
            { id: 2, name: 'Bob', age: 30 },
            { id: 3, name: 'Charlie', age: 35 }
        ];
        console.log(
            '%c id%c name%c age',
            'color: white; background-color: black; padding: 2px 10px;',
            'color: white; background-color: black; padding: 2px 10px;',
            'color: white; background-color: black; padding: 2px 10px;'
        );

        data.forEach((row) => {
            console.log(
                `%c ${row.id} %c ${row.name} %c ${row.age} `,
                'color: black; background-color: lightgray; padding: 2px 10px;',
                'color: black; background-color: lightgray; padding: 2px 10px;',
                'color: black; background-color: lightgray; padding: 2px 10px;'
            );
        });
    };
    const picture = (url, scale = 1) => {
        if (isProduction) return;
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => {
            const c = document.createElement('canvas');
            const ctx = c.getContext('2d');
            if (ctx) {
                c.width = img.width;
                c.height = img.height;
                ctx.fillStyle = 'red';
                ctx.fillRect(0, 0, c.width, c.height);
                ctx.drawImage(img, 0, 0);
                const dataUri = c.toDataURL('image/png');

                console.log(
                    `%c sup?`,
                    `font-size: 1px;
                    padding: ${Math.floor((img.height * scale) / 2)}px ${Math.floor((img.width * scale) / 2)}px;
                    background-image: url(${dataUri});
                    background-repeat: no-repeat;
                    background-size: ${img.width * scale}px ${img.height * scale}px;
                    color: transparent;
                    `
                );
            }
        };
        img.src = url;
    };

    return {
        info,
        error,
        warning,
        success,
        picture,
        table
    };
};
export default prettyLog

在需要的地方使用

import prettyLog from "@/utils/log/console.js"

init(){
       const log = prettyLog();
       log.info('YG','https://juejin.cn/user/501800125607752');
       log.info('杰仔加油');
       log.info('信息:','加多了杰仔爆胎了');
       log.error('奥德彪', '年轻要多吃点苦 因为老了就吃不动了');
       log.error('爱笑的人运气一般不会差,运气太差的人也笑不出来');
       log.warning('奥德彪', '领着三千的薪,受着万元的苦,这叫千薪万苦! ');
       log.success('奥德彪', '贫穷的爱情就像香蕉,不是绿了就是黄了,轮到你时说不定还黑了!');
      //  log.picture('https://gitee.com/esthergege/js/blob/master/vue/vuex/src/assets/123.png');//CORS跨域
      log.picture('https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0514%2Fd0ea93ebj00sdgx56001xd200u000gtg00hz00a2.jpg&thumbnail=660x2147483647&quality=80&type=jpg');
       const data = [
          { id: 1, name: '杰仔', age: 27 },
          { id: 2, name: '文阳', age: 26 },
          { id: 3, name: '加薪', age: 24 }
        ];
        console.table(data);
    }

这样在团队开发中大家统一使用log.info()输出调试信息,到了开发环境自动会关闭输出。

git源码下载

结束!