转换为Typescript后,模块没有默认导出 [英] Module has not default export after converting to Typescript
问题描述
我已将JavaScript代码转换为Typescript并收到错误
I have converted the JavaScript code to Typescript and getting the error
模块没有默认导出
Module has no default export
我尝试使用花括号导入,并使用module.exports导出,但是没有一个起作用.
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";
在api-routes.ts中,当我尝试导入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
如何导入而不会出现错误?我尝试使用从"./contactController"导入"{contactController}",但是效果不佳.
How can I import without the error? I have tried using "import {contactController} from "./contactController" but that did not work as well.
推荐答案
文档(请参见导出"和导入"部分): 以这种方式导入模块时:
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
需要具有默认导出.例如,可以通过以下方式完成此操作:
<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 = () => {
// ...
};
使用上面的代码,< whatever_name_I_want>
将是 foo
方法(一个模块只能具有 1 默认导出).为了同时导入 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>";
但是根据您要执行的操作,可能不需要使用默认导出.您可以使用 export
关键字简单地导出所有方法,如下所示:
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(...);
或全局变量中:
// api-routes.ts
import * as contactController from "./contactController";
// Usage
contactController.index(...);
contactController.create(...);
PS:我在 create
中重命名了您的 new
方法,因为"new"已经是一个JavaScript关键字.
PS: I renamed your new
method in create
because "new" is already a JavaScript keyword.
这篇关于转换为Typescript后,模块没有默认导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!