I've been using TypeScript here and there for web applications and have referenced public type definitions made available through Definitely Typed but one thing that has always eluded me is how one would go about creating reusable libraries in TypeScript with the purpose of being consumed by a TypeScript application or another library.
Most guidance on the topic seems to point directly to how one would create or find type definitions for libraries authored originally in JavaScript but what about libraries written in TypeScript, it seems that some mechanism for sharing the resulting js files and a corresponding type definition file should be something that is common place but I haven't been able to find any mention of anybody trying to do this for private or public libraries. Perhaps I'm looking in the wrong places? Is there a story for creating and consuming TypeScript libraries.
To create a TS library that will be consumed by a TS project you don't have to do a whole lot.
(Sorry if the example is overly verbose.)
Assuming your source files are writting in TypeScript, you need the following config tweaks:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"module": "commonjs",
"removeComments": false,
"sourceMap": true,
"outDir": "dist/",
"declaration": true
},
"filesGlob": [
"**/*.ts",
"!node_modules/**/*"
],
"exclude": [
"node_modules",
"typings/global",
"typings/global.d.ts"
],
"compileOnSave": true
}
The important thing here is basically declarations: true
, which tell the TS compiler to generate the d.ts files.
{
"name": "my-typescript-library",
"description": "...",
"version": "1.0.0",
"main": "./dist/my.service.js",
"typings": "./dist/my.service.d.ts",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
"typescript": "^1.8.10",
"typings":"^1.0.4",
...
}
}
The important things here is "main" and "typings" which is the entry point for the service in the library. So if someone were to require("my-typescript-library")
then the file listed here would be used. The typings field is similar but obviously helps TypeScript.
You then push this library to Github, or Bitbucket, or where ever.
You don't need much here.
Add a dependency to your library:
{
...,
"dependencies": {
"my-typescript-library": "git+ssh://bitbucket.org/you/my-typescript-library",
...
}
}
You will need an SSH key in this example.
Then you just import the lib.
import {MyService} from "my-typescript-library";
So there you have it, a TypeScript lib being used in a TypeScript app. Hope that is enough of an answer (and clear enough), otherwise just drop me a line.
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