LoginSignup
3
2

More than 5 years have passed since last update.

typescript & webpack 使用時に IE9 対策として空の console.* を用意する

Posted at

開発中のページを IE9 で参照したら真っ白な画面になりました。
原因を探るために開発者ツールを表示させると、今度はページが正常に表示されました。

?? となりましたが、IE9 には console が無いという、良く知られたことに起因していました。開発者ツールを表示させた時のみ console.* が有効になるので、正常に表示されるのです。

対策として、window.console が定義されていない時にはダミーを用意するという、良く知られた対応をすることにしました。typescript & webpack 使用時には以下のようにします。

console のダミーを定義する preload.ts

preload.ts
// IE9 doesn't implement console
class DummyConsole {
    assert(){}
    clear(){}
    count(){}
    debug(){}
    dir(){}
    dirxml(){}
    error(){}
    group(){}
    groupCollapsed(){}
    groupEnd(){}
    info(){}
    log(){}
    msIsIndependentlyComposed(){}
    profile(){}
    profileEnd(){}
    select(){}
    time(){}
    timeEnd(){}
    trace(){}
    warn(){}
}
const w:any = window; // cheat type check.
w.console || (w.console = new DummyConsole());

webpack の設定ファイルの entry point に上記のファイルを追加します。

webpack.config.js
module.exports = {
    entry: ["preload.ts", "index.ts"],
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2