简体   繁体   中英

Importing a typescript file without using any of the exports

I'm pretty new to TypeScript and I have a main.tc where I import items.tc, which contains and exports some item classes, and also adds the class types to an array from itemManager.tc. The problem is that they only get added to the array if I use atleast 1 export from items.tc in some way in main.tc, even just logging an export works.

Here is some shortened versions of my files:

main.tc

import * as Items from "./item";
import * as ItemManager from "./itemManager";

console.log(ItemManager.list) //List is empty

items.tc

import * as ItemManager from "./itemManager";

export class Item1
{
    constructor()
    {

    }
}
ItemManager.list.push(typeof Item1);

itemManager.tc

export const list = [];

If I added console.log(Items.Item1) to my main.tc, ItemManger.list will contain all the items, but doing that is not ideal. Is there a way to make sure an imported file gets run? or am I supposed to use something else than importing?

I'm using webpack to compile it to a single .js file, I don't know if that changes anything.

If you have a named import and the name is not used, the import is ignored.

For imports that have side-effects - and no names that you wish to use - you can use this syntax:

import "./some-module-with-side-effects";

From the documentation :

Import a module for side-effects only

Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports. To import these modules, use:

 import "./my-module.js"; 

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