node.jstypescripttypingtsdtypescript1.8

Typescript: Require a (new) TYPINGS file the correct way (in node)?


I am getting very confused with regards to importing a Typings file, there seems to be so many ways to do it.

I am writing a nodejs program.

I installed momentJS via typings (not an ambient module) and I have managed to import it like so

var testOne = require('moment/moment');

import * as testTwo from 'moment';

import * as testThree from 'moment/moment';

It seems all three ways are working. 1st option is the original node require way I am used to... the other 2 seem to be a typescript import.

I have used a single moment directory structure and moment/moment and they seem to equally work.

I am ignoring typings/browser...

So my directory structure for the moment is actually stored here

     /typings/main/definitions/moment/index.d.ts

So should I be using moment or moment/moment ?

I did try checking the docs and I don't know if I am just not understanding it correctly but which import do I use when?

And with regards to typings?

The typings command I used to install momentjs was

    typings install moment

Solution

  • Both import * as testTwo from 'moment'; and var testOne = require('moment'); are valid and the correct way of importing a module.

    The difference is that the first will load it's type definition in design time, intellisense will work and compiler will validate it on the fly (if your using an IDE that supports this stuff). In a TypeScript project, the first is preferred over the second. But the important thing here is that both compile and run as expected.

    import * as testTwo from 'moment/moment'; and var testOne = require('moment/moment'); are also valid, but should not be used.

    moment/moment module is created by typings (only inside moment.d.ts) when downloading the definition from the registry. It's a way they found to prevent conflicts. Take a look at the original moment.d.ts file from the registry, it's different from the file you have in your local system.

    More than that, you've choose a bad library to compare this. require('moment/moment') also works because there's a moment.js file inside root moment project path. But this is not common, not all packages does this and it should be avoided. Packages are meant to be used by simply referencing it's name.