Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

I'm giving a shot at typescript. It works fine at the hello world stage. I'm now trying to use a 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 at typescript documentation and in google didn't help. Other S/O questions are either unanswered (here and here) or unrelated.

Elements :

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

How do we consume a npm package in typescript ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[EDIT] Thanks a lot for this answer! However, as of 2018, it is outdated. Readers, have a look at the other answers.

There are several ways to import modules from npm. But if you don't get typings, tsc will always complain that it can't find the module you are requiring (even if transpiled js is actually working).

  • If you do have typings and do not use a tsconfig.json, use reference to import the typings:

    /// <reference path="path/to/typings/typings.d.ts" />
    
    import * as _ from 'lodash`;
    
    console.log(_.toUpper('Hello, world !'))
    
  • If you are using a tsconfig.json file, be sure to have your typings file included (or not excluded, your choice), and make the import like on the previous example.

In the case when there is no available typings. You have two choices: write your own on a .d.ts file, or ignore type checking for the library.

To completely ignore the type checking (this is no the recommended way), import the library on a variable of type any.

 const _: any = require('lodash');

 console.log(_.toUpper('Hello, world !'))

tsc will complain that require doesn't exist. Provide node typings, or declare it to discard the error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...