1

I am most probably missing some tsconfig option here.

What Im doing is pretty simple:

I am creating an npm module, for example:

export class HelloWorld {
    constructor(public greeting: string){}
}

with my tsconfig being:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "removeComments": true,
    "noImplicitAny": false,
    "preserveConstEnums": true,
    "declaration": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "../js"
  },
  "filesGlob": [
    "./**/*.ts",
    "!./node_modules/**/*.ts"
  ]
}

When my declaration is automatically created it looks like this:

export declare class HelloWorld {
    greeting: string;
    constructor(greeting: string);
}

But that doesnt work well when actually installing the npm package in other projects. When I import the package I have to use:

import hello = require("hello-world/js/index");

(for example)

I found out that when I wrap the declaration file in module declare module "hello-world" {...} Then I can import it as desired by import hello = require("hello-world");

Wrapping the generated definition file manually is not an option as it rewrites itself all the time, is there any option that would take name of the package from package.json and automatically wrap the definition in that module?

4
  • did you try 'export default class HelloWorld'? Commented Jun 10, 2016 at 15:01
  • @baryo yes doesnt make any difference Commented Jun 10, 2016 at 15:02
  • could you please post your package.json ? Commented Jun 10, 2016 at 15:22
  • Have a look at this article which explains where does typescript look for typings,etc: ivanz.com/2016/06/07/… Commented Jun 10, 2016 at 15:25

1 Answer 1

1

Make sure you have a typings property specified in package.json...

{
    "name": "hello-world",
    "typings": "hello-world.d.ts",
    ...etc...
}

...or change your definition file to be named index.d.ts.

Then after installing the package with these changes, the compiler will be able to resolve it when you write:

import hello = require("hello-world");

More details

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

2 Comments

import {HelloWorld} from 'hello-world'; new HelloWorld("greeting here"); instead of require ?
@IvanZlatev I always use es6 modules, but I just used require because they used it as well. My memory of exactly how require works is slowly fading to be honest :)

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.