Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 436
Thomas Avatar asked Jan 07 '17 02:01

Thomas


People also ask

Does ts not have default export?

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' .

How do I import and export interface in TypeScript?

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.


1 Answers

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";
like image 164
cartant Avatar answered Oct 04 '22 02:10

cartant