Can I dynamically import TypeScript modules into Node.js / Express?
I have a Node.js server built with Express.js and coded in TypeScript. Here's a snippet of a get call to my server:
server.ts
private get(req: Request, res: Response, next: NextFunction, objectName: string) {
var DatabaseObject = require("./models/" + objectName + ".js")(this.orm, Sequelize.DataTypes);
var Transform = require("./routes/" + objectName + ".js");
var transform = new Transform();
// ...
console.log(req.query["columns"]);
console.log(transform.columnWhitelist);
console.log(transform);
// ...
if (transform.columnWhitelist) {
console.log("Column Whitelist Exists.");
}
// ...
}
It dynamically loads the Sequelize module for the database object requested in the url and then tries to load the TypeScript module with rules about which columns can be selected, which columns can be requested, etc. Here's the start of my ruleset class:
account.ts
export default class Transform {
static columnWhitelist : Object = {"id": "id", "name": "name", "parentAccountId":"parentAccountId", "masterAccountId":"masterAccountId"};
constructor() { }
}
However, when I run my application, I get:
id,name,parentAccountId
undefined
{ default:
{ [Function: Transform]
columnWhitelist:
{ id: 'id',
name: 'name',
parentAccountId: 'parentAccountId',
masterAccountId: 'masterAccountId' } } }
When I make a call to transform.columnWhitelist, I get undefined even though I can see it in the generated JavaScript file. I've also tried just:
var transform = require("./routes/" + objectName + ".js");
Or:
var transform = require("./routes/" + objectName + ".js")();
But neither one nor the other works.
+3
source to share
2 answers
If you don't want to use
var transform = require("./routes/" + objectName + ".js").default;
You can export your class by doing
class Transform {
static columnWhitelist: Object = {"id": "id", "name": "name", "parentAccountId": "parentAccountId", "masterAccountId": "masterAccountId"};
constructor () {}
}
export = Transform;
After you do the following again:
var transform = require ("./ routes /" + objectName + ".js");
0
source to share