![](/img/trans.png)
[英]Import/Require nodejs modules without @types in Typescript in 2018
[英]require for modules in nodejs with typescript
按照 server.ts 中的代碼:
const express = require('express');
const athletesRouter = require('./src/routes/athletesRouter');
在控制台中運行node server.ts
,拋出:
錯誤:找不到模塊“./src/routes/athletesRouter”
如果我將 server.ts 更改為 server.js,將sportsRouter.ts 更改為sportsRouter.js,則一切正常。
這是我的 tsconfig.json:
{
"compilerOptions": {
"noImplicitAny": true,
"esModuleInterop": true,
"target": "esnext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
},
}
這是 .babelrc(雖然我不確定這是否相關):
{
"presets": [
[
"@babel/preset-typescript",
{
"targets": {
"node": "current"
}
}
]
]
}
我錯過了什么?
對此的解決方案是安裝ts-node ,然后在控制台中運行ts-node server.ts
這個 npm 包必須全局安裝才能使用該命令。
以下是擴展此主題的額外信息
有兩種情況:
開發環境:可以使用nodemon在更改代碼的同時重新加載服務器。 它的--exec
命令可用於運行ts-node
而無需將.ts
轉譯為.js
生產環境: .ts
代碼必須轉譯為.js
。 這可以通過打字稿中的tsc
命令來完成。 之后,使用 nodejs 中的node
命令。
可以在下面的package.json
中找到這種兩種場景方法的示例,其中使用了兩個腳本:
"scripts": {
"startDevelopment": "nodemon --exec ts-node server.ts",
"startProduction": "tsc && node server.js"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.