模块没有默认导出 | TypeScript RestAPI [已关闭]

问题描述 投票:0回答:1

在执行

controller
 时,
import controller from '../controllers/test.controller';

一词出现红色下划线

我有一个rest api typescript 应用程序。我的结构如图所示...project structure

我似乎不明白为什么我在

controller
下出现一条红线。这表示模块 'c:/users/home/desktop/RESTAPI_TS_NODEJS/source/controllers/test.controller 没有默认导出。 ts(1192)

在我的 package.json 里面我有..

{
  "name": "restapi_ts_nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "source/server.ts",
  "scripts": {
    "dev": "nodemon source/server.ts",
    "build": "rm -rf build / && prettier --write source/ && tsc"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/axios": "^0.14.0",
    "@types/express": "^4.17.21",
    "@types/morgan": "^1.9.9",
    "axios": "^1.6.7",
    "express": "^4.18.3",
    "morgan": "^1.10.0",
    "nodemon": "^3.1.0",
    "ts-node": "^10.9.2",
    "typescript": "^5.4.2"
  }
}

然后在我的 tsconfig.json 里面

{
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "allowSyntheticDefaultImports": true,
    "module": "commonjs",
    "esModuleInterop": true,
    "outDir": "./build",
    "rootDir": "./source",
    "target": "es6",
    "skipLibCheck": true,
    "strict": true
  }
}

我尝试通过在线阅读进行

import { controller } from '../controllers/test.controller';
,这是一个可能的解决方案,但它没有解决它。然后,我在 tsconfig.json 文件中将
allowSyntheticDefaultImports
添加到 true 作为另一个可能的解决方案,然后重新启动 vs code,没有出现相同的问题。

这是我在

test.ts
中的内容,它位于路由文件夹内。

import express from 'express';
import controller from '../controllers/test.controller';
const router = express.Router();

router.get('/testRoute', controller.testFunction);

export default router;`

这是我在控制器文件夹内的

test.controller.ts
中的内容

import { Request, Response, NextFunction } from 'express';
import axios, { AxiosResponse } from 'axios';

const testFunction = async (req: Request, res: Response, next: NextFunction) => {
    let result: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/com/todo/1');
    return res.send(result.data);
};
node.js typescript rest
1个回答
1
投票

在您的

test.controller.ts
文件中,没有
export
子句。

但是您将此文件导入为

test.ts
中的控制器。

请像这样更改您的代码。

import { Request, Response, NextFunction } from 'express';
import axios, { AxiosResponse } from 'axios';

const controller = (req: Request, res: Response, next: NextFunction) => {
    const testFunction = async (req: Request, res: Response, next: NextFunction) => {
        let result: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/com/todo/1');
        return res.send(result.data);
    };
}

export default controller

在你的

test.controller.ts

© www.soinside.com 2019 - 2024. All rights reserved.