【问题标题】:Node js + TypeSc + Babel "Error: Cannot find module 'koa'"Node js + TypeSc + Babel“错误:找不到模块'koa'”
【发布时间】:2020-04-25 08:47:23
【问题描述】:
  1. 我克隆了一个 demo 。安装 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,但我认为这不是一个好主意,你们如何解决?

【问题讨论】:

    标签: node.js typescript babeljs


    【解决方案1】:

    你有几个选择:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-13
      • 2019-05-13
      • 2016-03-23
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      相关资源
      最近更新 更多