简体   繁体   中英

Imports returning as a promise in TypeScript after migration

I'm trying to migrate my fairly large project to TypeScript and I'm having a hard time with imports.

I'm still fairly new at programming, so I have no idea if this was bad practice, but I had all my code from my helper and API functions in folders called "api" and "utilities". The following is a rough file tree of my file structure:

├── api
│   └── users.js
├── utilities
│   ├── db.js
│   └── templates.js
├── central.js
└── index.ts

Although I'll only put 3 files in all the examples I'll list here, there are actually a total of over 20 files and I really didn't want to require (or now in TS, import ) them manually whenever I needed them, so I created a central.js file with the following:

central.js

module.exports.db = require("./utilities/db.js")
module.exports.templates = require("./utilities/templates.js")
module.exports.users = require("./api/users.js")

As I migrated to TypeScript, I followed the TS docs's migration guide , but was not able to successfully get the central.js file (now central.ts) to work. The following is what I tried:

central.ts

const central:any = {}

central.db = import("./utilities/db")
central.templates = import("./utilities/templates")
central.users = import("./api/users")

export = central

Although it first appeared to work successfully, it threw an error saying TypeError: central.users is not a function when I ran the following code:

import central = require('./central');

// Code too long, but I used `central.users()` here

To troubleshoot, I logged what central was and it logged the following:

{
  db: Promise { <pending> },
  templates: Promise { <pending> },
  users: Promise { <pending> }
}

I am not sure if my issues are caused by the imports being promises or whatever else, but any help is appreciated. Also any advice on how to improve my file structure is also helpful.

First off: this isn't terrible practice. It's pretty standard to re-export a bunch of subcomponents in a file.

The slightly better way of exporting for what you're trying to do (without the issue of async imports) is as follows:

export * as db from "./utilities/db";
export * as templates from "./utilities/templates";
export * as users from "./api/users";

Now in your main file, import it as so:

import central from "./central";

console.log(central); // {db: ..., templates: ..., users:...} (notably without the promises)

I wish you luck with your migration!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM