2

I am trying to write a typescript library that is shared between a few other typescript applications. To do this I put each library as its own node module, and have the library set to emit its declaration file.

To test I have the shared library setup with one file:

lib\guid.ts

export class Guid {
    static EmptyGuid(): string {
        return '00000000-0000-0000-0000-000000000000';
    }
}

lib\tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "module": "amd",
    "noEmitOnError": true,
    "removeComments": false,

    "target": "es5",
    "sourceMap": true,
    "declaration": true,

    "outFile": "./lib/lib-b.js"
  },
  "exclude": [
    "node_modules",
    "!node_modules/@types",
    "lib"
  ]
}

I end up with a declaration file that looks like:

lib\lib-b.d.ts

declare module "guid" {
    export class Guid {
        static EmptyGuid(): string;
    }
}

And finally I set the node module to include the typing info:

lib\package.json

{
  "name": "lib-b",
  "version": "1.0.0",
  "description": "",
  "main": "./lib/lib-b.js",
  "typings": "./lib/lib-b.d.ts",
  "files": [
    "lib"
  ], 
  "author": "",
  "license": "ISC"
}

Now in the app that is using the library I bring it in using npm:

app\package.json

{
  "name": "web-app",
  "version": "1.0.0",
  "description": "",
  "main": "./lib/index.html",  
  "author": "",
  "license": "ISC",
  "dependencies": {
    "lib-b": "file:../LibB"
  }
}

And in one of its files I try to use the library like so:

import { Guid } from 'lib-b';

But that gives me the following error:

error TS2306: File '.../WebApp/node_modules/lib-b/lib/lib-b.d.ts' is not a module.

I have been looking around, but most examples I find talk about writing typings for an already existing JS library - I cant find much that talks about using the declaration file from existing typescript code. Should the declaration file be usable in other apps? Is there another way to build reusable typescript libraries?

3
  • Where is "file:../LibB"? Commented May 9, 2017 at 3:10
  • The file entry in the app points to the shared library module. Commented May 9, 2017 at 5:35
  • Do you need to use amd or can you use commonjs? Commented May 9, 2017 at 16:09

1 Answer 1

3

I end up with a declaration file that looks like:

Recommend using commonjs and follow the npm node_modules pattern. You will get a file like:

export class Guid {
    static EmptyGuid(): string;
}

More

Here is a quick start video https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.