IE 9- 瀏覽器中,未打開開發者工具時,window.console 為 undefined。直接調用 console.log() 會拋出「對象不支持該屬性或方法」錯誤,導致後續 JS 停止執行。
// 放在所有 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.config.js
module.exports = {
// ...
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 生產構建自動移除 console.*
pure_funcs: ['console.log', 'console.info', 'console.debug'] // 僅移除特定
}
}
})
]
}
};
// babel.config.js
module.exports = {
plugins: [
process.env.NODE_ENV === 'production' &&
['transform-remove-console', {exclude: ['error', 'warn']}]
].filter(Boolean)
};
// 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;
}
}
?debug=1 動態啟用 console 輸出,無需重新部署。