Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules (import/export) and classes. My question is: What is the most effective way to integrate these newly generated JavaScript files (compiled from TypeScript) into my existing JavaScript code? Let's say I have a class in TypeScript:

export default class DemoClass {

  public static sayHello() {
    console.log("Hello from demo class...");
  }
}
When this is compiled, it becomes:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DemoClass = /** @class */ (function () {
  function DemoClass() {
  }
  DemoClass.sayHello = function () {
    console.log("Hello from demo class...");
  };
  return DemoClass;
}());
exports.default = DemoClass;
//# sourceMappingURL=DemoClass.js.map
In my tsconfig.json file, I have set "module": "commonjs". Now, how can I require the DemoClass.js file from my legacy app.js and correctly invoke the sayHello() method? The following code seems to work, but I'm not sure if using "default" is the proper approach:

var DemoClass = require('./lib/DemoClass');
DemoClass.default.sayHello();

Answer №1

Instead of using export default, you can opt for export = for a different approach.

export = class NewDemoClass {
    public static sayBonjour() {
        console.log("Bonjour from the new demo class...");
    }
}

Check it out in the Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

Uploading files and data in Laravel using Vue.js and Vuetify: A step-by-step guide

My Vuetify form is working fine with text input, but when I try to include images, I encounter the error GET http://danza.test/thumbnails[object%20File] 404 (Not Found). How can I successfully pass both text and images in a form? This is part of the code ...

Identifying Gmail line breaks in the clipboard using Angular

I'm currently working on a feature that allows users to paste content from Gmail into a field and detect line breaks. The field doesn't have to be a text area, I just need to identify the line breaks. However, there seems to be an issue with det ...

forming an instance from JSON information

In a .json file, I have data that includes information on countries such as their currency, major language, and land area in square kilometers or square miles. { "countries": { "sweden": { "currency": "Swedish krona", " ...

Error message appears in Chrome console when using `emit` with socket.io client

While developing a simple application on Windows using the latest versions of nodejs and socket.io, I encountered an issue where the socket created on the client side resulted in unexpected output when socket.emit was called. The console in Google Chrome d ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Using a primary key in a relational database is crucial when utilizing an ORM tool such as Sequelize

As of now, I am involved in a nodejs project that involves utilizing Sequelize ORM to communicate with a Postgres database. When working with ORM like sequelize, should I utilize custom fields as primary keys in the database tables or stick with autogenera ...

What is causing the 'info' object to be undefined?

transporter.sendMail(mailOptions,(error,info)=>{ if(error) console.log(error) console.log('Message Sent: '+info.messageId) console.log('Preview URL: '+nodemailer.getTestMessageUrl(info)) res.redirect('contacts', ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Retrieving the name of the currently active express middleware function

Greetings to all! I have been an avid reader for a long time, but this is my first time reaching out with a question. My inquiry pertains to dynamically accessing function names in Express ^4.17.1. Despite thorough research on both the internet and the exp ...

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...

Error: You do not have permission on (Database name) to run this command

My tech stack includes Node.Js, Expressjs, mLab for database hosting, and mongoDB I encountered an authorization error on Streetinform (my DB name) while trying to execute the command: {listIndexes: "sessions", cursor: {}} This is the specific error I&ap ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Angular organizes the GET response in alphabetic order

Currently, I am working on developing an interactive table in Angular that displays information from a SQL database. The technology stack I have chosen to work with includes MSSQL, Express.js, and AngularJS. While logging the response in Node, I noticed t ...

Is there a way to direct NPM to search for installed packages in an alternate directory?

Issues with my Docpad installation. Currently, Docpad is located in /usr/bin/docpad and /usr/lib/node_modules. But NPM is searching in the directory /usr/local/bin/docpad and /usr/local/node_modules. Is there a way to specify the correct directory for n ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

Is conditional requirement necessary for Express?

Currently, I am utilizing the reload package during development. This particular package is listed under devDependancies within my package.json file. Within my app.js, the following code snippet can be found: if (process.env.NODE_ENV !== 'productio ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...