我已将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”导入“ {contactController}”,但是效果不佳。
答案 0 :(得分:2)
您需要更改导出到的方式:
const contacts: String[] = [];
// Handle index actions
const index = (req: any, res: any) => {
res.json({
data: contacts,
message: "Contacts retrieved successfully",
status: "success"
});
};
// Handle create contact actions
const newContact = (req: any, res: any) => {
// save the contact and check for errors
contacts.push("Pyramids");
res.json({
data: contact,
message: "New contact created!"
});
};
export default {index, newContact};
那么您应该可以像这样导入
import routes from './contactController';
答案 1 :(得分:2)
文档(请参见“导出”和“导入”部分): Typescript Modules Documentation。
以这种方式导入模块时:
// <some_file>.ts
import <whatever_name_I_want> from "<path_to_my_awesome_module>";
<my_awesome_module>.ts
需要具有默认导出。例如,可以通过以下方式完成此操作:
// <my_awesome_module>.ts
export default foo = () => { // notice the 'default' keyword
// ...
};
export bar = () => {
// ...
};
使用上面的代码,<whatever_name_I_want>
将是foo
的方法(一个模块只能具有 1 个默认导出)。为了同时导入bar
方法,您将必须分别导入它:
// <some_file>.ts
import <whatever_name_I_want>, { bar } from "<path_to_my_awesome_module>";
但是根据您要尝试执行的操作,可能不需要使用默认导出。您只需使用export
关键字即可导出所有方法,如下所示:
// contactController.ts
export index = (req: any, res: any) => { // no need for a default export
// ...
};
export create = (req: any, res: any) => {
// ...
};
并将它们都导入到括号中
// 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:我在new
中重命名了create
方法,因为“ new”已经是一个JavaScript关键字。