node.js - How to consume npm modules from typescript? -


i'm giving shot @ typescript. works fine @ hello world stage. i'm trying use npm module :

index.ts =

import _ = require('lodash')  console.log(_.toupper('hello, world !')) 

this doesn't work :

  • tsc index.ts -> cannot find module 'lodash'. (2307)
  • node-ts index.js -> cannot find module 'lodash'. (2307)

looking @ typescript documentation , in google didn't help. other s/o questions either unanswered (here , here) or unrelated.

elements :

  • typescript 1.8 latest
  • yes, lodash installed npm --save lodash , exists in filesystem (checked)
  • i did typings --save lodash
  • variants import * _ 'lodash' or const _ = require('lodash') don't work either
  • i tried tweaking tsconfig.json options suggested in other answers "moduleresolution": "node" , "module": "commonjs" suggested in answers, still doesn't work

how consume npm package in typescript ??

there several ways import modules npm. if don't typings, tsc complain can't find module requiring (even if transpiled js is actually working).

  • if have typings , not use tsconfig.json, use reference import typings:

    /// <reference path="path/to/typings/typings.d.ts" />  import * _ 'lodash`;  console.log(_.toupper('hello, world !')) 
  • if using tsconfig.json file, sure have typings file included (or not excluded, choice), , make import on previous example.

in case when there no available typings. have 2 choices: write own on .d.ts file, or ignore type checking library.

to ignore type checking (this no recommended way), import library on variable of type any.

 const _: = require('lodash');   console.log(_.toupper('hello, world !')) 

tsc complain require doesn't exist. provide node typings, or declare discard error.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -