require a TypeScript class in a Node CommonJS JavaScript file?Working with mongoose, in my TS code, I do:
// user.model.ts
export const UserModel = model<User>('User', schema);
In my JS code:
// user.controller.js
const UserModel = require('./user.model');
But I receive the following error message:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module './user.model'
code: 'MODULE_NOT_FOUND'
When I add .ts:
// user.controller.js
const UserModel = require('./user.model.ts');
^^^
The error message changes:
user.model.ts:1
import { Document, model, Schema } from 'mongoose';
^^^^^^
SyntaxError: Cannot use import statement outside a module
TypeScript files must be "transpiled" via the TypeScript compiler before they can be run or imported into vanilla JS. If you're working in Node, one of the best ways to do this is to utilize ts-node, which will automatically just-in-time transform your scripts as it runs them. See their docs here.