TypeError:超级表达式必须为null或函数,而不是Babeljs

时间:2016-03-03 16:42:27

标签: javascript node.js inheritance babeljs

我目前正在尝试在ES6中使用node.JS和Babel进行多文件继承(我使用Babel将代码从ES6转换为ES5'因为Node现在没有实现ES6)。 我正在使用导入/导出来“链接”不同的文件。

其实我有: 父类(文件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());

我正在测试来自Parent和Child的toString()方法调用 那么我使用Babel将代码从ES6转换为ES5并分别运行每个部分以测试它是否正常。
- Point(Parent)很好,并且无错误地执行 - ColorPoint(Child)不能完全运行并抛出:

  

TypeError:超级表达式必须为null或函数,而不是未定义的

StackTrace的第一行是:

  

function _inherits(subClass,superClass){if(typeof superClass!=='function'&& superClass!== null){throw new TypeError('super expression必须为null或函数,不是'+' 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; }   (它来自ES5转换代码(Babelified),如果需要,我可以完全发布。)

这令人沮丧,因为这段代码非常简单...... 但是我没有看到导致错误的原因。

我尝试不同版本的Babel(5,5.8,6),但没有差异......

我做错了什么?

PS:我忘了说:当我只在一个文件中执行此操作时,它完美运行。但是,按文件只有一个课程对我来说非常重要......

2 个答案:

答案 0 :(得分:39)

您的导出与导入不匹配:

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

您正在导出命名符号但导入默认符号,因此您将在第二个文件中获取错误的对象Point

您可以使用:

export default class Point

在第一个类文件或

import {Point} from './pointES5';

在第二个文件中获取正确的引用。如果您要使用单文件格式的布局,我建议使用前者。您通常只会导出一个类,因此将其作为默认值是有意义的。

你现在所拥有的相当于:

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

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

class SubPoint extends Point

答案 1 :(得分:1)

如果您将webpack用作捆绑程序,则这也可能是webpack配置中的问题。 或如何丑化您的代码。例如,我如何使用NPM软件包 react-draft-wysiwyg 和wepback插件 uglifyjs-webpack-plugin 解决了我的特定问题。

这里对我有用的是将 compress 选项的 inline 选项设置为false,因为默认情况下, true strong> uglifyOptions 。

optimization:{
  minimizer: [new UglifyJsPlugin({
  uglifyOptions: {
    compress: {
      inline: 1, // this right here
      // keep_fnames: true
    },
    mangle: {
      // keep_fnames: true
    }
  }
})]
}