How to use "import" properly in a Node.js application with typescript

Asked

Viewed 559 times

1

Good afternoon. I am writing a Rest API using node.js and typescript, but I’m having trouble using the import in some parts of the programme.

for example in my server.ts I have:

const connectDB = require("./config/db"); 

(That works smoothly.)

and I wanted to move her to:

import { connectDB } from "./config/db";

but I get the following error:

Could not find a declaration file for module './config/db'. d:/documents/projects/Node/Contact_keeper/config/db.js' implicitly has an 'any' type.ts(7016)

db.js:

const mongoose = require("mongoose");
const config = require("config");
const db = config.get("mongoURI");

const connectDB = async () => {

try{
    await mongoose.connect(db, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true
    });

    console.log("MongoDB Connected.")

}catch(err){
    console.log(err.message);
    //ends with a failure
    process.exit(1);
}
}

module.exports = connectDB;

I’m using module.exports, then I don’t understand why he doesn’t recognize it as a module.

Now, in another part of my code, I’m having another problem with the import, in rota de user I’m trying to bring a model user do mongoose, But when I try to change const user = require("../models/User"); for import { user } from "../models/User"; i get the following error:

Module '".. /.. /Contact_keeper/models/User"' has on Exported Member 'Userschema'. ts(2305)

But I do have an Xports there, so much so that with require() works smoothly.

Model User Mongoose

import mongoose, {Schema} from 'mongoose';

const UserSchema: Schema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    date:{
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('user', UserSchema);
  • 1

    If you are using TS, use the TS export syntax

  • @Costamilam that is the purpose of my question, I’m trying to use the import of TS but I have these errors, I don’t want to use require, but I’m using while I can not solve the problems with import.

  • 1

    The problem when it matters is because it’s not exporting with the TS

  • @Costamilam really, had not noticed that the export would be different in TS, I managed to pack everything here. Thank you very much!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.