Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module has not default export after converting to Typescript

I have converted the JavaScript code to Typescript and getting the error

Module has no default export

I have tried importing using the curly braces and exporting using module.exports but none of them 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, when I am trying to import the contactController module it is throwing the error

Module has no default export

How can I import without the error? I have tried using "import {contactController} from "./contactController" but that did not work as well.

like image 460
Dev Avatar asked Dec 22 '22 23:12

Dev


1 Answers

Documentation (see the "Export" and "Import" sections): Typescript Modules Documentation.

To complete Vasil's answer:

When you import a module this way:

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

<my_awesome_module>.ts needs to have a default export. For example, this can be done this way:

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

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

With the code above, <whatever_name_I_want> will be the foo method (a module can only have 1 default export). In order to import the bar method as well, you will have to import it seperately:

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

But according to what you're trying to do, there is probably no need to use a default export. You could simply export all your methods with the export keyword, like this:

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

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

and import them both either in brackets:

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

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

or in a global variable:

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

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

PS: I renamed your new method in create because "new" is already a JavaScript keyword.

like image 51
ttous Avatar answered Dec 26 '22 00:12

ttous