Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a class to extend with ES6 and Webpack?

I'm new to webpack and am trying to require or import a class to extend in another file, and continually end up with the class being undefined. Here's the file setup.

app.js

require('./stuff.js');

stuff.js

require('./Subclass.js');

Subclass.js

require('./Superclass.js');

class Subclass extends Superclass {
}

Superclass.js

class Superclass {
}

And compiling with webpack via webpack app.js bundle.js

With this I end up with Superclass is not defined when including bundle.js in the browser.

I have also tried using import with exports, doing

Subclass.js

import Superclass from './Superclass';

// I have also tried
// import {Superclass} from './Superclass';

class Subclass extends Superclass {
}

Superclass.js

export default class Superclass {
}

But that results in Superclass being undefined when trying to extend, causing the error Super expression must either be null or a function, not object

This is my webpack.config.js

var path = require('path');
var webpack = require('webpack');
module.exports = {
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    },
    stats: {
        colors: true
    },
    devtool: 'source-map'
};
like image 538
Elle H Avatar asked Oct 24 '25 03:10

Elle H


1 Answers

Your initial stab at it was wrong because:

  1. You aren't importing Superclass correctly
  2. You aren't exporting Subclass or Superclass

Your second attempt is closer as your importing Superclass correctly but again you fail export Subclass - to summarise, this should fix your code

Subclass.js

import Superclass from './Superclass';

export default class Subclass extends Superclass {
   ...
}

Superclass.js

export default class Superclass {
   ...
}
like image 87
James Avatar answered Oct 25 '25 17:10

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!