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.
The "Module has no default export" error occurs when we try to import as default from a module that doesn't have a default export. To solve the error make sure the module has a named export and wrap the import in curly braces, e.g. import {myFunction} from './myModule' .
Use a named export to export an interface in TypeScript, e.g. export interface Person{} . The exported interface can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With