Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using npm modules in Typescript

Tags:

npm

typescript

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"
  ]
}
like image 631
qwe asd Avatar asked Mar 30 '16 12:03

qwe asd


2 Answers

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.

like image 68
Amid Avatar answered Sep 28 '22 08:09

Amid


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
}
like image 25
Nahush Farkande Avatar answered Sep 28 '22 08:09

Nahush Farkande