【问题标题】:Cannot import module in nodejs with typescript无法使用打字稿在nodejs中导入模块
【发布时间】:2021-08-31 22:02:33
【问题描述】:

我正在使用 ExpressJS 和 Typescript。

我正在导入一个模块,但当我尝试 console.log 时我得到了未定义。一些模块可以导入并正常工作。但有些模块未定义。

我不明白为什么以及如何。任何人都有这个问题的经验。请帮帮我。

非常感谢!!

文件夹结构:

- dist/
- src/
  - api
  - database
  - middleware
  - routers
  - server.ts

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "rootDir": "./src",

    "strict": true,
    "noImplicitAny": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*", "src/**/*.json"]
}

server.ts中间件工作正常。

/* eslint-disable no-console */

import http from 'http';

import express, { Application, Request, Response } from 'express';

import middleware from './middleware';
import database from './database/models';

const app: Application = express();

app.use(middleware.appMiddleware); // The middleware work fine.

app.get('/', (_req: Request, res: Response) => {
  res.send('Welcome to Meet You website!');
});

const server = new http.Server(app);
const PORT = 3000;

database.sequelize.sync().then(() => {
  middleware.redis.start((error) => {
    if (!error) {
      server.listen(PORT, () => {
        console.log(`The server listen on port ${PORT}`);
      });
    }
  });
});

但是在 api/routers.ts 我的中间件是未定义的。

import { Router } from 'express';

import middleware from '../../middleware';

import signInController from './sign-in/controllers';
import signUpController from './sign-up/controllers';
import changePasswordController from './change-password/controllers';

const authRouters: Router = Router();

console.log('middleware', middleware); // undefined

authRouters.route('/sign-in').post(signInController);
authRouters.route('/sign-up').post(signUpController);
authRouters
  .route('/change-password')
  .put(middleware.jwt.verifyToken, changePasswordController);

export default authRouters;

中间件/index.ts

import appMiddleware from './app';
import jwt from './jwt';
import redis from './redis';

export default {
  appMiddleware,
  jwt,
  redis,
};

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

    您只需要在终端中运行以下命令:

    npm install @types/node
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2016-04-12
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      相关资源
      最近更新 更多