2 回答

TA貢獻1824條經(jīng)驗 獲得超5個贊
要完成Vasil的答案:
當您以這種方式導入模塊時:
// <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>";
但是根據(jù)您要嘗試執(zhí)行的操作,可能不需要使用默認導出。您可以使用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”已經(jīng)是一個JavaScript關鍵字。

TA貢獻1829條經(jīng)驗 獲得超7個贊
您需要將導出方式更改為:
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';
添加回答
舉報