Dev*_*Dev 4 javascript express typescript
我已将 JavaScript 代码转换为 Typescript 并收到错误
模块没有默认导出
我曾尝试使用花括号导入并使用 module.exports 导出,但它们都不起作用。
联系人控制器.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!"
});
};
Run Code Online (Sandbox Code Playgroud)
api-route.ts
import contactController from "./contactController";
Run Code Online (Sandbox Code Playgroud)
在 api-routes.ts 中,当我尝试导入 contactController 模块时,它抛出错误
模块没有默认导出
如何在没有错误的情况下导入?我曾尝试使用“从“./contactController”导入{contactController},但效果不佳。
您需要将导出方式更改为:
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};
Run Code Online (Sandbox Code Playgroud)
然后你应该能够像这样导入
import routes from './contactController';
Run Code Online (Sandbox Code Playgroud)
文档(请参阅“导出”和“导入”部分): Typescript 模块文档。
当您以这种方式导入模块时:
// <some_file>.ts
import <whatever_name_I_want> from "<path_to_my_awesome_module>";
Run Code Online (Sandbox Code Playgroud)
<my_awesome_module>.ts需要有一个默认的 export。例如,这可以通过以下方式完成:
// <my_awesome_module>.ts
export default foo = () => { // notice the 'default' keyword
// ...
};
export bar = () => {
// ...
};
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,<whatever_name_I_want>将是foo方法(一个模块只能有1 个默认导出)。为了也导入该bar方法,您必须单独导入它:
// <some_file>.ts
import <whatever_name_I_want>, { bar } from "<path_to_my_awesome_module>";
Run Code Online (Sandbox Code Playgroud)
但是根据您要执行的操作,可能不需要使用默认导出。您可以简单地使用export关键字导出所有方法,如下所示:
// contactController.ts
export index = (req: any, res: any) => { // no need for a default export
// ...
};
export create = (req: any, res: any) => {
// ...
};
Run Code Online (Sandbox Code Playgroud)
并在括号中导入它们:
// api-routes.ts
import { index, create } from "./contactController";
// Usage
index(...);
create(...);
Run Code Online (Sandbox Code Playgroud)
或在全局变量中:
// api-routes.ts
import * as contactController from "./contactController";
// Usage
contactController.index(...);
contactController.create(...);
Run Code Online (Sandbox Code Playgroud)
PS:我重命名了您的new方法,create因为“new”已经是一个 JavaScript 关键字。