nodejs+TS项目使用es6导入报错模块未找到Error: Cannot find module '@/config/env',请问是什么问题?

代码如下

// env.ts
import * as dotenv from 'dotenv';

dotenv.config();

export const { APP_PORT } = process.env;
// main.ts
import Koa from "koa";
import { APP_PORT } from "@/config/env";

const app = new Koa();

app.use(async (ctx) => {
  ctx.body = 'Hello World!'
})

app.listen(APP_PORT, () => {
  console.log(`server is running on http://localhost:${APP_PORT}`);
})

export default app;
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    ...
    },
    "typeRoots": [
      "./node_modules/@types"
    ],
    "types": [
      "module-alias",
    ],
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    /* Type Checking */
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}
// package.json
{
   "scripts": {
      "dev": "npx nodemon --exec ts-node ./src/main.ts",
  },
}
阅读 1.9k
1 个回答

tsconfig.json 里缺少 compilerOptions.paths,导致 TS 不认识 @ 缩写,于是就报错找不到模组。

简单来说这样即可:

{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏