"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue:

The module has no default export

I tried importing using curly braces and exporting with module.exports, but neither solution worked.

contactController.ts

const contacts: String[] = [];

// Handle index actions
exports.index = (req: any, res: any) => {
    res.json({
        data: contacts,
        message: "Contacts retrieved successfully",
        status: "success"
    });
};

// Handle create contact actions
exports.new = (req: any, res: any) => {

     // save the contact and check for errors
    contacts.push("Pyramids");

    res.json({
            data: contact,
            message: "New contact created!"
        });
};

api-route.ts

import contactController from "./contactController";

In the api-routes.ts file, when attempting to import the contactController module, I received the error:

The module has no default export

How can I resolve this import error? I also tried using "import {contactController} from "./contactController" without success.

Answer №1

Check out the documentation for TypeScript modules: Typescript Modules Documentation.

Expanding on Vasil's response:

When importing a module like this:

// <some_file>.ts
import <whatever_name_I_want> from "<path_to_my_awesome_module>";

The file <my_awesome_module>.ts must have a default export. Here's an example:

// <my_awesome_module>.ts
export default foo = () => { // using 'default' keyword
  // ...
};

export bar = () => {
  // ...
};

In the code above, <whatever_name_I_want> will represent the foo method since a module can only have 1 default export. To import the bar method as well, you'll need to do it separately:

// <some_file>.ts
import <whatever_name_I_want>, { bar } from "<path_to_my_awesome_module>";

However, in most cases, there's no necessity for a default export. You can simply use the export keyword to export all methods like so:

// contactController.ts
export index = (req: any, res: any) => { // no default export needed
  // ...
};

export create = (req: any, res: any) => {
  // ...
};

And then import both either within brackets:

// api-routes.ts
import { index, create } from "./contactController";

// Usage
index(...);
create(...);

or through a global variable:

// api-routes.ts
import * as contactController from "./contactController";

// Usage
contactController.index(...);
contactController.create(...);

PS: I changed the name of your new method to create because "new" is already a reserved JavaScript keyword.

Answer №2

To successfully export, modify your code to:

const contactsList: String[] = [];

// Handling index actions
const renderIndex = (req: any, res: any) => {
    res.json({
        data: contactsList,
        message: "Contacts retrieved successfully",
        status: "success"
    });
};

// Managing new contact creations
const createNewContact = (req: any, res: any) => {

     // Saving the contact and handling errors
    contactsList.push("Pyramids");

    res.json({
            data: contact,
            message: "New contact created!"
        });
};

export default {renderIndex, createNewContact};

Once modified, you can import them as follows

import routes from './contactController';

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

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

The type 'Text' does not have a property named 'then'

Transitioning from .js to typescript. When I changed the file extension from .js to .ts while keeping the same code, I encountered an error stating Property 'then' does not exist on type 'Text'.ts in the then((value) method. The return ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

Unable to identify TypeScript version in Visual Studio Code, causing TS Intellisense to not function properly

Global Installation of TypeScript Below is what I see in my terminal when I run the command tsc --version. tsc --version // Version: 3.8.3 The TypeScript "version" is not showing up in the Status bar. When I try to select the TypeScript version fr ...

Squire.js failing to replace mock dependency while utilizing store

Exploring Squire.js as a dependency loader for RequireJS. Testing in a standard web browser environment to run unit tests. Attempting to utilize store to access my mocks, but struggling with preventing Squire from loading the actual module. The usage of m ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

An effective way to pass a value using a variable in res.setHeader within express.js

Attempting to transmit a file on the frontend while including its name and extension. var fileReadStream = fs.createReadStream(filePath); res.setHeader("Content-disposition", `attachment; filename=${fileName}`); fileReadStream.pipe(res); Encount ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function: // update table PropertyWindow.prototype._update = function (text) { if (text === void 0) { text = "&lt;no properties to display&gt;"; } this._propertyWindow.html(text); ...

Encountering 401 unauthorized error in Laravel Passport, Vue.js, and Axios integration

I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios for making API requests. Below is the script code from my App.vue file: import axios from 'axios'; export default { da ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Incorporate personalized design elements within the popup component of Material-UI's DataGrid Toolbar

I am in the process of customizing a Data Grid Toolbar component by making adjustments to the existing Grid Toolbar components sourced from Material-UI. For reference, you can view the official example of the Grid Toolbar components here. Upon clicking o ...

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

Utilize the Expect --upload-file header in your curl request to interface with Node.js

Struggling with uploading a file to Autodesk using the View and Data API, I am having trouble figuring out how to send curl by http or request lib. Specifically, I'm unsure of how to set the expect header. Below is the curl command I have been trying ...

Converting a JavaScript function to TypeScript with class-like variables inside: a step-by-step guide

During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention: const wai ...

Do we really need to invest time in understanding views and template engines in Express, if we have already mastered Angular within the MEAN Stack?

My journey with the MEAN Stack began by learning Angular through the official website (angular.io). Currently, I am delving into node.js and express.js. I have a question regarding the use of Angular for the front end in the MEAN Stack. If Angular is hand ...

Encountering Error ENOENT while running Gulp Build Task with SystemJS in Angular 4

UPDATE: 2020.02.13 - It seems like another individual encountered the same issue, but no solution was found. Check out Github for more details. An array of GulpJS errors is emerging when attempting to construct an Angular 4 Web App with SystemJS. The str ...

Is it feasible to develop a TypeScript module in npm that serves as a dual-purpose tool, functioning as both a command line utility

My goal is to develop an npm TypeScript module that serves dual purposes - acting as a command line utility and exporting methods for use in other modules. The issue arises when the module intended for use as a command line utility requires a node shebang ...

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...