简体   繁体   English

我如何在没有整个模块的情况下将输入内容导入Typescript?

[英]How can I just import typings into Typescript, without the whole module?

I am writing a piece of Express middleware in Typescript. 我正在用Typescript编写Express Express中间件。 It will be published to npm as a standalone package. 它将作为独立软件包发布到npm。 I would like to be able to define my functions using Express types, as this lets me write with type safety: 我希望能够使用Express类型定义函数,因为这使我可以使用类型安全性进行编写:

function playWithRequest( req: express.Request, res: express.Response, next: express.NextFunction ) {
    req['key'] = 'stuff';
}

module.exports = playWithRequest;

However, I have no need to require('express') itself, and I want to avoid import statements that will generate such a require() call. 但是,我不需要require('express')本身,并且我想避免将产生此类require()调用的import语句。 How can I tell Typescript about the express types without importing express itself? 如何在不导入express本身的情况下告诉Typescript有关express类型的信息?

The express typings are installed by npm install @types/express , and are thus hanging around in node_modules/@types/express/index.d.ts . Express npm install @types/expressnpm install @types/express ,因此挂在node_modules/@types/express/index.d.ts

By default TypeScript will not transpile an import to require statement, which has no JS-only exports used in the compiled file. 默认情况下,TypeScript不会将导入转换为require语句,该语句在编译文件中不使用仅JS导出。

So no require call will be generated when you only use the types exported by @types/express . 因此,仅使用@types/express导出的类型时,不会生成require调用。

When you make such module ( that needs express only for typings ) you can safely put @types/express into your dependencies ( not devDependencies ) and keep express module inside your devDependencies ( for compilation purposes ). 当您制作这样的模块(只需要express @types/express )时,可以安全地将@types/express放入您的依赖项(不是devDependencies)中,并将express模块保留在devDependencies中(出于编译目的)。

By doing this whenever you install your module to your application it will be properly safe-typed but it won't complain that express is not there. 这样,无论何时将模块安装到应用程序中,它都将被正确地安全键入,但不会抱怨Express不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM