16

I would like to use npm module in Typescript project but there is no typings or tsd for this module. When I try use import Module from 'module' I had an error : Cannot find module 'module'. Is there way to fix it?

[EDIT] My tsconfig.json:

{
  "compilerOptions": {
    "target": "ES5",
    "moduleResolution": "node",
    "module": "commonjs",
    "noEmitOnError": true,
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "sourceRoot": "src",
    "outDir": "bld"
  },
  "exclude": [
    "bld"
  ]
}
qwe asd
  • 1,598
  • 3
  • 21
  • 31
  • Has been answered in [this other S/O question](http://stackoverflow.com/questions/38224232/how-to-consume-npm-modules-from-typescript) – Offirmo Jul 06 '16 at 16:37

3 Answers3

18

I assume your question is related to importing the module

import Module from 'module'

And not exporting it as you stated. If this is the case your can fall back to plain javascript and require module like this:

var Module = require('module');

[EDIT]

Verify that in tsconfig.json you have the following lines in compiler options:

"compilerOptions": { 
    "moduleResolution": "node",
    "module": "commonjs"
}

Hope this helps.

Amid
  • 21,508
  • 5
  • 57
  • 54
  • 1
    Yes, it's question about importing. For me doesn't work both variants. I guess, the problem is that there is no type definition for `module`, and typescript don't looking for it in `node_modules`. But I don't know how to fix it. – qwe asd Mar 31 '16 at 08:03
  • No you do not need type definitions for the second version. Check updated answer. – Amid Mar 31 '16 at 08:10
  • 1
    I fixed tsconfig.json according to your changes, but had the same error: `Cannot find module 'module'`. Check updated `tsconfig.json`, please – qwe asd Mar 31 '16 at 08:26
  • Have you installed the module? can you verify that the module's folder is present in your 'node_modules' folder? – Amid Mar 31 '16 at 08:28
  • Yes, module is in "node_modules" folder – qwe asd Mar 31 '16 at 08:30
  • 1
    The only thing that comes to mind is that your module is not compiled targeting commonjs. You can test this with using any other module without definitions. Take for example 'merge2' install it via npm and verify that `var merge = require('merge2');` works. – Amid Mar 31 '16 at 08:36
2

In case you wish not to pollute your imports with requires, you can follow the following method.

You can create a module.d.ts definition file which contains the following

declare module Module {}

Your imports should work now.

If you wish to import something like

import { abc } from 'module';

just go ahead and add the following to module.d.ts

declare module Module {
    export let abc: any
}
Nahush Farkande
  • 5,290
  • 3
  • 25
  • 35
0

By example: npm install numwords

Then added the import the .ts file: import * as numwords from 'num-words';

And then the usage: console.log((numwords(5));

jmpeace
  • 179
  • 2
  • 10