我正在尝试将一个对象从一个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"
}
}
1条答案
按热度按时间lrl1mhuk1#
由于您使用的是
type=module
,因此需要使用.js
扩展,请参阅在package.json和新扩展中键入我尝试复制您的示例,并通过使用以下依赖项添加
.js
来运行它:在node v16和v19上进行了测试。我猜测您使用的是过时的typescript/node版本,该版本不完全支持ESM。另外请注意,您应该使用
await connectToDB();
等待安装完成。