node.js 如何从打字稿中使用 npm 模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38224232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:23:01  来源:igfitidea点击:

How to consume npm modules from typescript?

node.jstypescriptnpmtsc

提问by Offirmo

I'm giving a shot at typescript. It works fine at the hello world stage. I'm now trying to use a npm module :

我正在尝试打字稿。它在 hello world 阶段运行良好。我现在正在尝试使用 npm 模块:

index.ts=

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)
  • 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 (hereand here) or unrelated.

查看打字稿文档和谷歌没有帮助。其他 S/O 问题要么没有答案(这里这里),要么不相关。

Elements :

元素:

  • typescript 1.8 latest
  • Yes, lodash is installed npm i --save lodashand 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
  • 打字稿 1.8 最新
  • 是的,lodash 已安装npm i --save lodash并存在于我的文件系统中(已选中)
  • 我也做了 typings i --save lodash
  • 变体import * as _ from 'lodash'const _ = require('lodash')不起作用
  • 我试图调整tsconfig.json选择在其他的答案建议 "moduleResolution": "node",并"module": "commonjs"在一些答案建议,仍然无法正常工作

How do we consume a npm package in typescript ??

我们如何在打字稿中使用 npm 包?

采纳答案by Offirmo

[2018/12] New, up-to-date, answer to this question I asked in 2016, which stills shows a lot of activity despite having outdated answers.

[2018/12] 我在 2016 年提出的这个问题的最新答案,尽管答案已经过时,但仍然显示出很多活动。

Long story short, TypeScript requires type informationsabout your package's code (a.k.a. "type declaration files" a.k.a. "typings") and rightfully tells you that you would otherwise be losing the whole point of TypeScript. There are several solutions to provide them or opt out of them, listed here in order of best practice:

长话短说,TypeScript 需要关于你的包代码的类型信息(又名“类型声明文件”,又名“类型”),并正确地告诉你,否则你将失去 TypeScript 的全部意义。有几种解决方案可以提供它们或选择不使用它们,此处按最佳实践的顺序列出:



Solution 0: the module already provides the typings. If its package.json contains a line like this:

解决方案 0:模块已经提供了类型。如果它的 package.json 包含这样一行:

"typings": "dist/index.d.ts",

it is already TypeScript-enabled. It's most likely not the case if you are reading this page, so let's continue...

它已经启用了 TypeScript。如果您正在阅读此页面,情况很可能并非如此,所以让我们继续...



Solution 1: use community-contributed typings from DefinitelyTyped. For a module "foo", try this:

解决方案 1:使用来自绝对类型的社区贡献的类型。对于模块“foo”,试试这个:

npm add -D @types/foo

if it works, Hymanpot! You now have the typings and can use your module. If npm complains that it can't find the module @types/foo, let's continue...

如果有效,大奖!您现在拥有了类型并可以使用您的模块。如果 npm 抱怨它找不到模块@types/foo,让我们继续......



Solution 2: provide custom typings about this module. (with an option to do zero effort)

解决方案 2:提供有关此模块的自定义类型。(可以选择做零努力)

  1. Create a folder named "typings-custom" at the root of your project
  2. Reference the content of this folder in your tsconfig.json:
  1. 在项目的根目录创建一个名为“typings-custom”的文件夹
  2. 在 tsconfig.json 中引用此文件夹的内容:
"include": [
    "./typings-custom/**/*.ts"
]
  1. Create a file with this exact name: foo.d.ts [foo = the name of the module] with the content:
  1. 创建一个具有以下确切名称的文件:foo.d.ts [foo = 模块的名称],内容如下:
declare module 'foo'

Your TypeScript code should now compile, albeit with NO type information (TypeScript consider the foo module of type "any").

您的 TypeScript 代码现在应该可以编译了,尽管没有类型信息(TypeScript 考虑了类型为“any”的 foo 模块)。

You can also attempt to write the type information yourself, looking at the official docand/or at examples from DefinitelyTyped. If you do, think of contributing your typings either directly into the module (solution 0, if the module author accepts) or into DefinitelyTyped (solution 1)

您也可以尝试自己编写类型信息,查看官方文档和/或来自绝对类型的示例。如果您这样做,请考虑将您的类型直接贡献到模块(解决方案 0,如果模块作者接受)或绝对类型(解决方案 1)

回答by Blackus

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

[编辑] 非常感谢您的回答!但是,截至2018年,它已经过时了。读者,看看其他答案。

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

有多种方法可以从 npm 导入模块。但是如果你没有打字,tsc总是会抱怨它找不到你需要的模块(即使转译的 js确实在工作)。

  • If you do have typings and do not use a tsconfig.json, use referenceto 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.jsonfile, be sure to have your typings file included (or not excluded, your choice), and make the importlike on the previous example.

  • 如果您确实有类型并且不使用 a tsconfig.json,请使用reference导入类型:

    /// <reference path="path/to/typings/typings.d.ts" />
    
    import * as _ from 'lodash`;
    
    console.log(_.toUpper('Hello, world !'))
    
  • 如果您使用的是tsconfig.json文件,请确保包含您的打字文件(或不排除,您的选择),并import在前面的示例中进行类似操作。

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

在没有可用类型的情况下。您有两种选择:在.d.ts文件上编写自己的文件,或者忽略库的类型检查。

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

要完全忽略类型检查(这不是推荐的方法),请在类型为 的变量上导入库any

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

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

tscwill complain that requiredoesn't exist. Provide nodetypings, or declareit to discard the error.

tsc会抱怨require不存在。提供类型node,或declare丢弃错误。

回答by Derek Soike

You're probably missing the Declaration Files.

您可能错过了Declaration Files

See DefinitelyTypedfor more info.

有关更多信息,请参阅绝对类型



Try this:

尝试这个:

npm install --save lodash
npm install --save @types/lodash

Now you can import.

现在可以导入了。

import _ from 'lodash';


If the module you're importing has multiple exports, you can do this:

如果您要导入的模块有多个 exports,您可以这样做:

import { Express, Router } from 'express';


If the module you're importing "has no default export"you need to do this:

如果您要导入的模块“没有默认导出”,则需要执行以下操作:

import * as http from 'http';

回答by Quynh Ngo

It worked for me.

它对我有用。

  1. Create a folder named "typings".
  2. In typings folder, create a file name module-name.d.ts. It contains:

    declare module "module-name";

  3. In tsconfig.json, refer to the folder

    "typesRoots": [ "./typings", "../node_modules/@types" ]

  1. 创建一个名为“typings”的文件夹。
  2. 在 Typings 文件夹中,创建一个文件名module-name.d.ts。它包含了:

    declare module "module-name";

  3. 在 tsconfig.json 中,参考文件夹

    "typesRoots": [ "./typings", "../node_modules/@types" ]