繁体   English   中英

Node js + TypeSc + Babel“错误:找不到模块'koa'”

[英]Node js + TypeSc + Babel “Error: Cannot find module 'koa'”

  1. 我已经克隆了一个演示 安装 koa、koa-router 等后,出现错误。 这是我的 index.ts 文件
import Koa from "koa"
import Router from "koa-router"
import logger from "koa-logger"
import json from "koa-json"

const app = new Koa()
const router = new Router()

router.get("/",async(ctx: any,next: any)=>{
    ctx.body = {
        meg:"Hello world"
    }
    await next
})

app.use(logger())
app.use(json())
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000,()=>console.log("app is running at 3000"))

这是我的 package.json

{
  "name": "babel-typescript-sample",
  "version": "0.7.2",
  "license": "MIT",
  "scripts": {
    "type-check": "tsc --noEmit",
    "type-check:watch": "npm run type-check -- --watch",
    "build": "npm run build:types && npm run build:js",
    "build:types": "tsc --emitDeclarationOnly",
    "build:js": "babel src --out-dir lib --extensions \".ts,.tsx\" --source-maps inline"
  },
  "devDependencies": {
    "@babel/cli": "^7.8.3",
    "@babel/core": "^7.8.3",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/preset-env": "^7.8.3",
    "@babel/preset-typescript": "^7.8.3",
    "@types/koa": "^2.11.3",
    "typescript": "^3.7.5"
  },
  "dependencies": {
    "koa": "^2.11.0",
    "koa-bodyparser": "^4.3.0",
    "koa-json": "^2.0.2",
    "koa-logger": "^3.2.1",
    "koa-router": "^8.0.8"
  }
}

我的文件结构看起来像:

/-------
  -lib
    -index.js
    -index.d.ts
  -node_modules
  -src
    -index.ts
  1. 实际上,在此之前,当我运行npm run build时,我收到错误src/index.ts:2:20 - error TS2307: Cannot find module 'koa-router'. 我自己写koa-router.d.ts ,但我认为这不是一个好主意,你们如何解决?

结构

你有几个选择:

  1. 使用npm install --save-dev @types/koa-router安装koa-router类型。
  2. moduleResolution中的 moduleResolution 设置为node 请参阅此处了解差异。 请注意,此选项仅在依赖项包含类型时才有效。 在这种情况下,它没有,所以第一个选项会更正确。
  3. 在 tsconfig.json 中编辑paths (指向目录)或types (指向.d.ts )以指向您的类型。 是的,为现有依赖项编写类型(“手动”)通常被认为是一个坏主意,因为它可能会更新并因此破坏你的类型。 如果依赖项没有类型,你可以通过使用 JSDoc 生成它来贡献它,如果它使用 JavaScript。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM