TypeError: Illegal constructor when trying to create a new instance of a class of another script file

Viewed 1723

I created a library of about 25 custom Web Components using LitElement + WebPack. The library contains components (e.g. context menus component) and views (e.g. custom table which also uses the context menu component).

So far, all components and codes were in one javascript file. To make the package more modular, I created a second entry point. Now all ui-components have their dependency graph as well as the special matrix table view.

entry: {
  'ui-components': './src/index.js',
  'view-matrix': './src/view-matrix.js'
},

In WebPack (v4) I'm using splitChunks Optimization:

optimization: {
    splitChunks: {
        chunks: 'all',
    },
}

If I now want to instantiate a ui component (defined and imported in /src/index.js) in view-matrix.js, I'm getting the following error.

1) Instantiation (view-matrix.js:31)

import {MwNavigationContextmenu} from "./components/navigations/mw-navigation-contextmenu";
    
let contextMenu = new MwNavigationContextmenu();

2) Error Message

TypeError: Illegal constructor (view-matrix.js:31)

Instantiating the same line of code in index.js works perfectly fine.

I made sure, MwNavigationContextmenu was defined as a custom web component before:

window.customElements.define('mw-navigation-contextmenu', MwNavigationContextmenu);

3) MwNavigationContextmenu definition

./components/navigations/mw-navigation-contextmenu

import { MwNavigationContextmenu } from './src/MwNavigationContextmenu.js';

window.customElements.define('mw-navigation-contextmenu', MwNavigationContextmenu);

./src/MwNavigationContextmenu.js

import {html, LitElement} from 'lit-element';

export class MwNavigationContextmenu extends LitElement {
  static get properties() {
    return {
      // defined props
      // hasbutton: {type:Boolean},
    };
  }

  constructor() {
    super();
    // property defaults following
    // this.hasbutton = true;
  }

  render() {
    return html`
      Render context menu…
    `;
  }
}

So there problem is kind of that MwNavigationContextmenu was defined in index.js and view-matrix.js can't instantiate classes then for whatever reason.

1 Answers

I became suspicious about shared components between multiple entry points and found a hint in a similar webpack issue case: https://github.com/webpack/webpack/issues/6977#issuecomment-388826616

Problem (as far as I understood it): Scripts from two entry points are loaded on the same page (whereas Webpack 4 has this rule of thumb: 1 entry point = 1 page). Therefore, a shared runtime chunk must be generated instead of using the splitChunks property.

Solution (edit webpack.config.js)

optimization: {
  runtimeChunk: {
    name: 'shared',
  },
}

Thanks to GitHub's akx https://akx.github.io/

Related