在nodejs中使用 ts + module

234 阅读1分钟

在nodejs中使用es6的import语法,需要在package.json添加以下字段

//package.json
{
    "module": "commonjs",  
}

新建 app.ts 文件

import express from 'express'
import cors from 'cors'

const app = express()
app.use(cors({origin:'*'}))

app.listen(8000,function(){
    console.log('正在监听 8000 端口')
})

运行 node app.ts 发现报错

image.png

需要先下载依赖

pnpm add  ts-node-dev @types/node typescript

然后添加 tsconfig.json 配置

{
    // other settings..
    "compilerOptions": {
      // other compiler options...
      "esModuleInterop": true,
 //      "module": "ESNext", // "module": "CommonJS" should work too
      "module": "commonjs",  
      "moduleResolution": "Node"
    },
    "include": ["/**/*.ts"],
    "exclude": ["node_modules"]

然后把 package.json 中的 type:module 移除

成功 运行 ts-node-dev app.ts