首页 > 解决方案 > ES6 模块如何在 Node/Express 路由应用程序中与 app.get 一起使用?

问题描述

我决定在 NodeJS/Express 项目中使用新的 ES6 导出而不是使用模块导出。我正在阅读 MDN 文档,它说 export 的使用方式如下:

export function draw(ctx, length, x, y, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, length, length);

在这里,我尝试在此app.get函数中以相同的方式使用它,但我的编辑器抛出语法错误。我应该使用其他格式吗?- 我实际上是在尝试将路由容器分成单独的文件以进行组织 - 然后最后将它们导入我的主 app.js 文件以使用 express 进行路由声明。

 export app.post('/exampleroute', async (req, res) => {
   ...
 });

// Error: Declaration or Statement expected.

标签: javascriptnode.jsexpressecmascript-6es6-modules

解决方案


您必须导出一个(默认值或命名变量)。

的返回值app.post()没有用。

要么导出函数:

export const myRouteHandler = async (req, res) => {
   ...
};

进而:

import { myRouteHandler } from "./myModule";
app.post('/exampleroute', myRouteHandler)

或者,导出路由器:

import express from 'express';
export const router = express.Router();

router.post('/exampleroute', async (req, res) => {
   ...
});

然后导入并使用它:

import { router } from "./myModule";
app.use("/", router);

推荐阅读