NodeJS 从 typescript 文件导入

laik7k3q  于 2023-04-20  发布在  Node.js
关注(0)|答案(1)|浏览(99)

我正在尝试将一个对象从一个typescript导入到另一个typescript文件。下面是我的代码:

import mongoose from "mongoose";
import Note from './models/notes';
import User from './models/users';
import express, { Request, Response } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';

dotenv.config();

const app = express();

app.use(cors());
app.use(express.json());

const PORT = process.env.PORT || 5000;
const URI = process.env.ATLAS_URI as string;

const connectToDB = async () => {
    try {
        await mongoose.connect(URI);
        console.log('Connected to MongoDB');
        app.listen(PORT, () => console.log(`Server running on port: ${PORT}`));
    } catch (err) {
        console.log(err);
    }
};
connectToDB();

我的文件结构是

server
    /dist
        index.js
        /models
            users.js
            notes.js
    /node_modules
    /src
        index.ts
        /models
            users.ts
            notes.ts
    package.json
    package-lock.json
    .env
    tsconfig.json
  • (我没有使用webpack或babel)*

我试着这样做:
import User from '../dist/models/users.js'
或者这个
import User from './models/notes.js
但这给了我错误,我很确定这不是正确的方法。
顺便说一句,这是我的tsconfig.json

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "ES2022",
        "rootDir": "./src",
        "outDir": "./dist"
        "moduleResolution": "node",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true
    }
}

我错过了什么?😢

编辑1这是我的users.ts文件:

import { Schema, Document, model } from 'mongoose';

interface IUser {
    email: string;
    password: string;
}

interface IUserModel extends IUser, Document { }

const UserSchema = new Schema({
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
}, { timestamps: true });

const User = model<IUserModel>('User', UserSchema);

export default User;

编辑2我得到这个错误:

无法找到从“...\server\dist\index.js”导入的模块“...\server\dist\models\users”
typescript import被编译为js,如下所示:

import User from './models/users';

编辑3Here's my package.json

{
    "name": "server",
    "version": "1.0.0",
    "description": "",
    "main": "",
    "type": "module",
    "scripts": {
        "start:ts": "tsc -w",
        "start:js": "concurrently \"nodemon dist/index.js\" \"nodemon dist/models/users.js\" \"nodemon dist/models/notes.js\" ",
        "start": "concurrently npm:start:*"
    },
    "keywords": [],
    "author": "Alex",
    "license": "ISC",
    "dependencies": {
        "@types/cors": "^2.8.13",
        "@types/express": "^4.17.17",
        "@types/mongoose": "^5.11.97",
        "concurrently": "^8.0.1",
        "cors": "^2.8.5",
        "express": "^4.18.2",
        "mongoose": "^7.0.3"
    }
}
lrl1mhuk

lrl1mhuk1#

由于您使用的是type=module,因此需要使用.js扩展,请参阅在package.json和新扩展中键入
我尝试复制您的示例,并通过使用以下依赖项添加.js来运行它:

...
    "nodemon": "^2.0.22",
    "tsc": "^2.0.4",
    "typescript": "^5.0.4"

在node v16和v19上进行了测试。我猜测您使用的是过时的typescript/node版本,该版本不完全支持ESM。另外请注意,您应该使用await connectToDB();等待安装完成。

相关问题