プログラマーのあああブログ

プログラミングなどなど (PHP, node, Golangとか書いてます)

Babelでコンパイルしたclassの "[class名] is not a constructor" エラーの対処

Babelでコンパイルしたモジュールをrequire()で使おうとしたら、以下のエラーメッセージがでました。

"[class名] is not a constructor"


例えばこんな風にclassを作ってBabelでコンパイルして

export default class dog {
...
}

そしてrequire() でモジュールを読み込んでインスタンスを生成すると

const Dog = require('dog');
const dog = new Dog();

//
"Dog is not a constructor"

"Dog is not a constructor" とエラーになります。

importを使ってたら問題ないので気が付つかなかった。


対処方法は以下のように default プロパティを使うか、

const Dog = require('dog').default;

または、Babelに babel-plugin-add-module-exports プラグインを入れてコンパイルすれば大丈夫です。

// .babelrc
{
  "presets": ["env"],
  "plugins": [
    "add-module-exports"
  ]
}




参考

Unexpected “Uncaught TypeError: XXX is not a constructor” errors with Babel and ES6

babel-plugin-add-module-exports