Search code examples
typescriptimportbundletypescript-typings

limit cost of importing typescript types from 3rd party libraries?


My main question is: If I import a type from a 3rd party library once into my project, and then import/export it several times internally, do I still incur the expense that I would from importing it each time directly from the 3rd party library?

Background:

I've recently started using an excellent vscode extension called import-cost which shows you the size of the packages you import. E.g.:

import { cloneDeep } from 'lodash'; 70.7K
import cloneDeep from 'loadash/cloneDeep'; 14.9K // way better!!

This has made me much more conscious of how everything I import will ultimately affect my final bundle size. One particular issue I've noticed, is with importing TypeScript types from 3rd party libraries. To import just one type, you still need to import the whole package. E.g.:

import { IComponentOptions } from 'angular'; 168.3K // Not cool!!!

If this can't be ameliorated in some way, I'm just not sure it's worth it.

So, my question is: rather than importing this type every time I write a component, directly from angular, if I do something like the following, is it any less costly than importing it each time directly from angular? Example:

path/to/my/project/types/shims.d.ts

export { IComponentOptions } from 'angular';

path/to/my/project/components/myComponent/myComponent.cmpt.ts

import { IComponentOptions } from "../../types/shims";
import controller from './myComponent.ctrl';
import template from './myComponent.tpl.html';

const myComponent: IComponentOptions = {
  template,
  controller,
  bindings: {
    someBinding: '@'
  }
};

export default myComponent;

If the IComponentOptions interface is imported from the shims file several times like this across my project, do I still incur the expense of the import each time, or is the concept of sharing across files internally less costly?

The overall question has larger implications than just typescript typings, but this is the particular use-case that sparked this at the moment.

If anyone can answer this, I would much appreciate it! Thank

POST-ANSWER EDIT:

As pointed out by the accepted answer, this actually seems to be a bug with the import-cost extension, as importing just types from libraries should not result in the module's code being imported. I've opened an issue here to hopefully resolve this issue.

Since the question does have further reaching implications, the other answer is also very useful, and it is important to note that although import-cost will show you the cost of each import, if you import something multiple times, it is no more costly than importing something once.


Solution

  • Actually I think the plugin is wrong. You can check the resuting JavaScript code, but imports that import only types from a module will be elided, as the types are not used in expressions. See FAQ