min read

Differences working with Typescript library modules vs Java modules

How things work in Java

When working with library modules in Java, you basically create your module within the root project, hook it to the root project (depending on your Build Tool Gradle / Maven), and then import it in your application module. (Very simplified)

All Java classes, enums and interfaces of the library with a public modifier will become available to your application module.

How things work in Typescript

All files you want to expose to other modules need to be exported. This does not only mean you need to use the export keyword in each file, but you also have to delegate those exports up to the root index.ts file, which is then registered in the package.json

{
  "name": "@my-workspace/my-library",
  "version": "0.0.1",
  "type": "module",
  "main": "./index.ts",
  "typings": "./types/index.ts"
}

Type declarations need to be explicitly registered in the package.json as well.

index.ts location

The location of the index.ts file in a TypeScript library can impact the import name of the module, especially if you're importing the module using a path that includes the directory containing the index.ts file.

For example, suppose you have a TypeScript library with the following directory structure:

my-library/
  index.ts
  src/
    index.ts

If you import this module in another TypeScript file using the path relative to the project root:

import { SomeClass } from './my-library';

In this case, since the index.ts file is located directly inside the my-library directory, TypeScript will automatically look for and find the index.ts file and import the module accordingly. The module will be imported with the name my-library.

However, if you move the index.ts file to a subdirectory within my-library, let's say src/utils/index.ts, the import statement would change to reflect this:

import { SomeClass } from './my-library/utils';

In this case, the directory structure and the location of the index.ts file impact the import path and thus the import name of the module.

It's important to note that you can always use an explicit import path to import modules regardless of the location of the index.ts file. For example:

import { SomeClass } from './my-library/src';

In this case, you are importing directly from the src directory, bypassing the index.ts file. This approach allows for more flexibility in managing your project structure.

In Java you do not rely on the name of the module itself anymore during imports, but on the path of the actual file within its folder structure. You specify the module itself just once in the build tool.