JavaScript の場合、Internet Explorer が F12 を押さずに console.log を処理できるようにするための次の解決策を見つけました。 「コンソール」は Internet Explorer の未定義エラーです
ただし、Typescript で次の行を使用すると、コンパイルできません。
if (!console) console = {log: function() {}};
何か案は?
JavaScript の場合、Internet Explorer が F12 を押さずに console.log を処理できるようにするための次の解決策を見つけました。 「コンソール」は Internet Explorer の未定義エラーです
ただし、Typescript で次の行を使用すると、コンパイルできません。
if (!console) console = {log: function() {}};
何か案は?
You are getting an error because the object literal you wrote doesn't have all the same members as a regular console
. Simplest fix would just be to type-assert as any
:
if (!console) console = <any>{log: function() {}};
Obviously you'll need to not call anything off console
other than log
.
これを処理する最も簡単な方法は、コンソールを抽象化することです...
class Logger {
static log(message: string) {
if (typeof window.console !== 'undefined') {
window.console.log(message);
}
}
}
Logger.log("Works with the console and doesn't ever error");
これにより、メッセージウィンドウでコンソールなしのシナリオを処理したり、サーバーにエラーを記録したり、コンソールに記録する以外にやりたいことをしたりするなど、他の可能性も開かれます-コードの実行も簡単になりますウィンドウのないコンテキストで!
console.js を見てください。すべてのブラウザでのコンソール ロギングなどを処理します。typescript でコンパイルするには、console.d.ts モジュール定義で console.log を定義し、console.log を使用する場所で d.ts ファイルを参照する必要があります。