2016-03-03 3 views
6

現在、私は現在、ES6でnode.JSとBabelを使用して複数のファイルの継承を試みています(Babelを使用してES6からコードを変換していますES5に接続すると、Nodeは現在ES6を実装していません)。 私は異なったファイルを "リンク"するためにインポート/エクスポートを使用しています。TypeError:スーパー式はnullまたはBabeljsで未定義でない関数

実際に私があります。 親クラス(ファイル1)

export class Point 
{ 
    constructor(x, y) 
    { 
     this.x = x; 
     this.y = y; 
    } 

    toString() { 
     return '(' + this.x + ', ' + this.y + ')'; 
    } 
} 

そして: 子クラス(ファイル2)

import Point from './pointES5' 

export class ColorPoint extends Point 
{ 
    constructor(x, y, color) 
    { 
     super(x, y); 
     this.color = color; 
    } 

    toString() { 
     return super.toString() + ' in ' + this.color; 
    } 
} 

そしてメイン メイン(ファイル3)

import Point from './pointES5' 
import ColorPoint from './colorpointES5' 

var m_point = new Point(); 
var m_colorpoint = new ColorPoint(); 

console.log(m_point.toString()); 
console.log(m_colorpoint.toString()); 

私は、toString()メソッドの呼び出しをParentとChildからテストすることにしています。
それでは、Babelを使ってコードをES6からES5に変換して、別々に各部分を実行してOKかどうかをテストします。
- Point(親)が良好で、エラーなく実行されます。
- ColorPoint(子供)完全に実行し、スローされません。

TypeError: Super expression must either be null or a function, not undefined

のStackTraceの最初の行は次のとおりです。

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.proto = superClass; } (It comes from the ES5 converted code (Babelified), and I can post it entirely if it's needed).

それは、このコードは非常にシンプルでイライラする原因となっています... しかし、私は何が原因でエラーが表示されません。

私はバベル(5、5.8、6)の貴様のバージョンを試してみたが何も違いはありません...私は間違っ

何をしましたか?

PS:私が言うことを忘れてしまった:完璧に私がそれを1つのファイルで行うとき。あなたが名前のシンボルをエクスポートするが、デフォルトを読み込む

export class Point 
// and 
import Point from './pointES5' 

、あなたはので:しかし、それはあなたのエクスポートがあなたのインポートと一致していません...ファイルによってのみ一つのクラスを持っている

答えて

24

私にとって本当に重要です2番目のファイルに間違ったオブジェクトをPointとして取得します。

こともできますし、使用:最初のクラスファイル内

export default class Point 

または

import {Point} from './pointES5'; 

第二のファイルの右の参照を取得します。ファイルごとの単一クラスのレイアウトを検討しているなら、前者をお勧めします。通常、エクスポートされるクラスは1つのみであるため、そのクラスをデフォルトとして使用することは理にかなっています。いまいましいうわー

// in Point 
module.exports = { 
    Point: Point 
}; 

// in ColorPoint 
var Point = require('./pointES5'); // will point to *the whole object* 

class SubPoint extends Point 
+0

は何あなたが今持っていることに相当します!私はもう少し "デフォルト"のキーワードが何であるか、それが現在使われているものを理解しています!手伝ってくれてどうもありがとう ! これは完璧に動作します! :D – Aethyn

+0

バンドル用にwebpackを使用している場合は、@ssubeで提案されている2番目のアプローチを使用することをお勧めします。これはパフォーマンス目的でwebpackの2.0ツリーの揺れを利用します。http://2ality.com/2015/12/webpack -tree-shaking.html –

関連する問題