Angular libraries using import shorthands

If you are authoring a library for Angular applications, your code may contain imports like the following:

import {InternalService} from './core';

This is a very basic TypeScript import that just loads something internal from the core of your library.

The path to core actually doesn’t resolve into a path at first, because it just links to a folder called core/ .

Imports like this only work if there is a index.ts file in the given folder. TypeScript automatically loads the core/index.ts file under the hood.

src/
|- core/
|-- index.ts # File that will be imported "under-the-hood"
|- the-importer.ts # File that contains the import statement.

The import shorthand works fine for development and for the most bundlers.

But a few bundlers like SystemJS are not able to understand those. This causes your library to not work properly for SystemJS users.

Note: There are still ways to configure SystemJS to load index files for directory imports.. But this is super painful for your users!

This doesn’t mean that you should switch to more explicit imports, because the import shorthands are definitely very convenient.

When using the Angular Compiler-CLI, the import shorthands will be automatically converted into more explicit import statements like:

import {InternalService} from './core/index';

Notice: This feature only works when targeting ES2015 /(ES6) and if your library will be annotated for closure.

Because as soon as you specify the annotateForClosureCompiler option inside of your tsconfig.json , the Angular compiler will use a tool called tsickle to convert your shorthand imports into the explicit imports.

"angularCompilerOptions": {
"annotateForClosureCompiler": true
}
See Jason Aden’s Talk about packaging libraries: https://goo.gl/7gqZBr

Using this explained approach will ensure that your library will work for all of your users without any struggle.

Also, you, as a library author, can still take advantage of the import shorthands for development!

Thanks for reading. Let me know if you have any questions!

— @devversion on Twitter.