Richard
Richard

Reputation: 61

Call `super` on JavaScript instance method

I'm attempting to call super on an instance method of an ES6 style class, and I'm getting parcel/babel build errors.

@parcel/transformer-babel: 'super' is only allowed in object methods and classes. (1291:21)

My code effectively looks like this

class BaseClass {
    constructor(params) {
        this.params = params;
    }

    matches(other) {
        // do some matching logic
        return true; // or false
    }
}

class MyClass extends BaseClass {
    matches(other) {
        let match = super.matches(other);
        // do some additional matching logic
        return true; // or false
    }

}

The error is when I call super.matches(other) in MyClass.

All the documentation I can find on super talks about its use in constructor, which is fine, and its use in static methods, but I have found no mention of instance methods.

Does this just not work in JS, am I doing it wrong, or is it something to do with the babel transformer or parcel?

Upvotes: 3

Views: 396

Answers (1)

Andrew Stegmaier
Andrew Stegmaier

Reputation: 3777

Parcel v2 supports transpiling es6 class syntax by default using swc. One "gotcha" is that if it detects a .babelrc/babel.config.json file in your project, it will switch to transpiling using babel, and then it is up to you to make sure that the config you provided will transpile classes.

According to the docs:

if you're only using @babel/preset-env, @babel/preset-typescript, and @babel/preset-react, Babel may no longer be necessary. Parcel supports all of these features automatically without a Babel config, and Parcel's default transpiler is much faster than Babel.

So the first thing I would try is just deleting any .babelrc/babel.config.json files in your project so you can try it out with swc. If that doesn't work (maybe because you're doing something else that swc doesn't support), make sure that @babel/preset-env is included in your babel config.

Upvotes: 1

Related Questions