【问题标题】:How are ES6 modules used with app.get in a Node/Express routing application?ES6 模块如何在 Node/Express 路由应用程序中与 app.get 一起使用?
【发布时间】:2021-04-07 04:19:16
【问题描述】:

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

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.

【问题讨论】:

  • 你想在那里导出什么样的绑定?您想如何导入和使用该路线? app 是什么(即它来自哪里)?

标签: javascript node.js express ecmascript-6 es6-modules


【解决方案1】:

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

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);

【讨论】:

  • 还有一个后续问题?假设我在第一个答案中具有路由器发布功能使用的依赖项。我是否可以在导出 router.post 模块的文件中包含这些依赖项? - 而不是将依赖项放在原始导出的模块文件中?我所说的依赖是指(const,require fs等)
  • 依赖关系不会在模块之间泄漏。您必须将值导入到使用它的范围内。
猜你喜欢
  • 2018-10-20
  • 2012-05-31
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 2019-10-31
相关资源
最近更新 更多