I'm looking to create an easy way for users to extend various services within a nodejs
app. It uses electron
, webpack
, and babel
.
I found a handy way to dynamically require
every file in a given folder:
// At the top of my class file
const thing_files = require.context('./things', false, /\.js$/)
// In my class constructor
this.things = {};
thing_files.keys().forEach(key => {
try {
this.things[key.replace(/(\.\/|\.js)/g, '')] = thing_files(key).default; // edit: also tried default()
} catch(err) {
process.send({message:`unable to add thing ${key}`});
}
});
This works great for files that look like the following:
export default {
getName() {
return 'thangythang';
}
}
However, it doesn't work when I export a class:
import Thing from "../base-thing";
export default class extends Thing {
constructor() {
super();
}
getName() {
return 'thangythang';
}
}
Nor with a named class:
export default class ThingOne extends Thing {
These classes otherwise work well when I require
them as expected:
const ThingOne = require('./things/thing-one')
var thing = new ThingOne.default();
process.send({message:`thing: ${thing.getName()}`}); // thing: thangythang
How can I work with them using webpack
's require.context
?