user3033194
user3033194

Reputation: 1831

Backbone View is not a constructor error in Webpack due to import order

I have a backbone view in 1 file which I am trying to instantiate in another, 'entry' file. An output file is bundled using Webpack and the entry file is loaded first in the output file, before the view code. Something like this:

index.js:

import $ from 'jquery';
import { Book } from './views/Book';

$(document).ready(function () {
  new Book();
});

Book.js

import Backbone from 'backbone';

const Book = Backbone.View.extend({
  tagName: 'li',

  template: _.template('<%= name %>'),

  render: function () {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

export default Book;

On running the project, I get this error in the console:

TypeError: __WEBPACK_IMPORTED_MODULE_1__views_Book__.Book is not a constructor
    at HTMLDocument.<anonymous> 
index.js:5 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_1__views_Book__.Book is not a constructor

When running webpack, I get this warning:

WARNING in ./js/index.js
5:6-10 "export 'Book' was not found in './views/Book'

I saw some posts on circular dependencies, but don't think that is the problem here. Can someone help please? Thanks!

Upvotes: 1

Views: 283

Answers (2)

user3033194
user3033194

Reputation: 1831

OK, the fix was altering the entry point in my webpack config file. I changed the entry point from:

entry: '/index.js'

to

entry: [SRC_DIR + '/views/main.js', SRC_DIR + '/index.js']

This ensured the dependencies(in main.js) were loaded first, followed by the index.js file. Hence in the bundled output file, the dependencies (in this case Book view) were implemented before initializing them. The problem was thus not in the code I posted, but in the configuration file of Webpack.

Upvotes: 0

Fran&#231;ois Richard
Fran&#231;ois Richard

Reputation: 7055

if you use

export default Book

then you need to load it this way

import Book from './views/Book';

export Book

would work with

import { Book } from './views/Book';

Upvotes: 1

Related Questions