猿问

转换为Typescript后,模块没有默认导出

我已经将JavaScript代码转换为Typescript并收到错误


模块没有默认导出


我尝试使用花括号导入和使用module.exports导出,但它们均无效。


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";

在api-routes.ts中,当我尝试导入contactController模块时,它将引发错误


模块没有默认导出


如何导入而不会出现错误?我尝试使用“ ./contactController”中的“ import {contactController}”,但是效果不佳。


一只萌萌小番薯
浏览 1208回答 2
2回答

沧海一幻觉

要完成Vasil的答案:当您以这种方式导入模块时:// <some_file>.tsimport <whatever_name_I_want> from "<path_to_my_awesome_module>";<my_awesome_module>.ts需要有一个默认导出。例如,可以通过以下方式完成此操作:// <my_awesome_module>.tsexport default foo = () => { // notice the 'default' keyword&nbsp; // ...};export bar = () => {&nbsp; // ...};使用上面的代码,<whatever_name_I_want>将成为foo方法(一个模块只能有1个默认导出)。为了同样导入该bar方法,您将必须单独导入它:// <some_file>.tsimport <whatever_name_I_want>, { bar } from "<path_to_my_awesome_module>";但是根据您要尝试执行的操作,可能不需要使用默认导出。您可以使用export关键字简单地导出所有方法,如下所示:// contactController.tsexport index = (req: any, res: any) => { // no need for a default export&nbsp; // ...};export create = (req: any, res: any) => {&nbsp; // ...};并将它们都导入到方括号中:// api-routes.tsimport { index, create } from "./contactController";// Usageindex(...);create(...);或在全局变量中:// api-routes.tsimport * as contactController from "./contactController";// UsagecontactController.index(...);contactController.create(...);PS:我重命名了您的new方法,create因为“ new”已经是一个JavaScript关键字。

千巷猫影

您需要将导出方式更改为:const contacts: String[] = [];// Handle index actionsconst index = (req: any, res: any) => {&nbsp; &nbsp; res.json({&nbsp; &nbsp; &nbsp; &nbsp; data: contacts,&nbsp; &nbsp; &nbsp; &nbsp; message: "Contacts retrieved successfully",&nbsp; &nbsp; &nbsp; &nbsp; status: "success"&nbsp; &nbsp; });};// Handle create contact actionsconst newContact = (req: any, res: any) => {&nbsp; &nbsp; &nbsp;// save the contact and check for errors&nbsp; &nbsp; contacts.push("Pyramids");&nbsp; &nbsp; res.json({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: contact,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: "New contact created!"&nbsp; &nbsp; &nbsp; &nbsp; });};export default {index, newContact};然后,您应该可以像这样导入import routes from './contactController';
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答