萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

避免 console 導致 IE 報錯:安全的調試代碼兼容模式

問題根源

IE 9- 瀏覽器中,未打開開發者工具時,window.console 為 undefined。直接調用 console.log() 會拋出「對象不支持該屬性或方法」錯誤,導致後續 JS 停止執行。

通用兼容方案:偽造 console 對象


// 放在所有 JS 執行前 (如基礎庫最頂部)
(function() {
    if (!window.console) {
        window.console = {};
    }
    
    // 定義所有標準方法為空函數
    var methods = [
        'log', 'debug', 'info', 'warn', 'error',
        'assert', 'dir', 'dirxml', 'group', 'groupEnd',
        'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'
    ];
    
    var noop = function() {};
    
    for (var i = 0; i < methods.length; i++) {
        var method = methods[i];
        if (!window.console[method]) {
            window.console[method] = noop;
        }
    }
})();

進階版:保留開發環境輸出、生產環境靜默


(function() {
    var isDebug = location.hostname === 'localhost' || 
                  location.hostname === '127.0.0.1' ||
                  location.search.indexOf('debug=1') > -1;
    
    if (!window.console) window.console = {};
    
    var methods = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 
                   'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace'];
    
    methods.forEach(function(method) {
        var original = window.console[method];
        if (isDebug && original) {
            // 開發環境:保留原功能,綁定 console 上下文
            window.console[method] = function() {
                return original.apply(window.console, arguments);
            };
        } else {
            // 生產環境/無 console:空函數
            window.console[method] = function() {};
        }
    });
})();

現代構建工具自動處理

Webpack / Vite / Rollup


// webpack.config.js
module.exports = {
    // ...
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    compress: {
                        drop_console: true, // 生產構建自動移除 console.*
                        pure_funcs: ['console.log', 'console.info', 'console.debug'] // 僅移除特定
                    }
                }
            })
        ]
    }
};

babel-plugin-transform-remove-console


// babel.config.js
module.exports = {
    plugins: [
        process.env.NODE_ENV === 'production' && 
        ['transform-remove-console', {exclude: ['error', 'warn']}]
    ].filter(Boolean)
};

TypeScript 類型聲明擴展 (避免 TS 報錯)


// global.d.ts
interface Console {
    log(...args: any[]): void;
    debug(...args: any[]): void;
    info(...args: any[]): void;
    warn(...args: any[]): void;
    error(...args: any[]): void;
    // ... 其他方法
}

// 確保 window.console 存在
declare global {
    interface Window {
        console: Console;
    }
}

最佳實踐總結

  1. 基礎庫頂部引入兼容代碼:確保所有業務代碼安全調用 console。
  2. 生產構建自動清理:配置 Terser/Babel 移除 console,減小體積、避免洩露敏感信息。
  3. 保留 error/warn:生產環境保留錯誤級日誌,便於 Sentry 等監控上報。
  4. 調試開關:URL 參數 ?debug=1 動態啟用 console 輸出,無需重新部署。
  5. 不要在庫代碼中直接調用 console:封裝統一 logger,內部判斷環境再決定輸出。
copyright © 萬盛學電腦網 all rights reserved