Webpack - Dynamically importing a class

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Webpack - Dynamically importing a class



I'm trying to dynamically import a class when a router condition is met.



I have no problems importing a standard (non-class) module, as this works as expected:


Router.on(
'/:region/map': (params) =>
import("Controllers/map.js" /* webpackChunkName: "map" */).then((map) =>
map.initialise(params.region);
);

);



But trying to do the same with a class is not working as expected.


Router.on(
'/:region/map': (params) =>
import("Controllers/map.js" /* webpackChunkName: "map" */).then(Map =>
Map.initialise(params.region);
);

);



Which fails 'e.initialise is not a function';



I also try to instantiate the class by using the new keyword:


new


Router.on(
'/:region/map': (params) =>
import("Controllers/map.js" /* webpackChunkName: "map" */).then(Map =>
const MapClass = new Map();
MapClass.initialise(params.region);
);

);



But still no joy!



How do I dynamically import a class in this scenario?



UPDATE:



This is my Map module, as a non-class module, which works:


var map =
initialise(region)
console.log("Map initialised for region: " + region);


export map ;



This is the same module but as a Class:


export default class Map
constructor()
//

initialise(region)
console.log("Map initialised for region: " + region);






can you also share map.js code. want to see how you export from and what you export from map.js
– Mohit Tilwani
Aug 10 at 12:03





@MohitTilwani - added. Thanks.
– Martin James
Aug 10 at 12:10




1 Answer
1


class Map
constructor()
//

initialise(region)
console.log("Map initialised for region: " + region);



export Map




Router.on(
'/:region/map': (params) =>
import("Controllers/map.js").then(( Map )=>
const MapClass = new Map();
MapClass.initialise(params.region);
);

);



can you try the above code and see are you getting Class in console





Thanks, Mohit. When I do this I get: ƒ n()!function(n,e)if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")(this,n),this.currentRegion=null
– Martin James
Aug 10 at 12:27


ƒ n()!function(n,e)if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")(this,n),this.currentRegion=null





can you try now. I edited the above answer. Also if it doesn't work, always try consoling the things from backwards. Like what are you getting in module and all
– Mohit Tilwani
Aug 10 at 13:12







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS