typescript 在 Angular 5 中,如何导入没有 @types 的 NPM 模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48761882/
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
In Angular 5, how can I import NPM modules with no @types
提问by ALansmanne
I'm trying Angular 5, starting a project from angular-cli. In this project, I would like to use a NPM module : J2M (https://github.com/kylefarris/J2M), so I looked online and saw these two commands :
我正在尝试 Angular 5,从 angular-cli 开始一个项目。在这个项目中,我想使用一个NPM模块:J2M(https://github.com/kylefarris/J2M),所以我在网上看了一下,看到了这两个命令:
npm install j2m --save
npm install @types/j2m --save-dev
Unfortunately, @types/j2m doesn't exist at all. So I tried to find a way to define my own typings but didn't manage to succeed...
不幸的是,@types/j2m 根本不存在。所以我试图找到一种方法来定义我自己的类型,但没有成功......
I'm using this code :
我正在使用此代码:
import * as J2M from "j2m";
...
console.log(J2M.toM(value));
But either "j2m" is not recognized, or "toM" is not a function, based on the samples I found online...
但是根据我在网上找到的示例,要么无法识别“j2m”,要么“toM”不是函数...
So, what's the proper way to import this module?
那么,导入这个模块的正确方法是什么?
Thanks,
谢谢,
回答by
You need to add the scripts into your angular-cli.json
file.
您需要将脚本添加到您的angular-cli.json
文件中。
Under the scripts
property, add
在scripts
属性下,添加
'../node_modules/path/to/minified/js.js'
If a style is required, you must also add it under your styles
property, in the same file.
如果需要样式,您还必须将其添加到您的styles
属性下,在同一文件中。
Once you did that, your library is imported. This means you don't need to use such things as
一旦你这样做了,你的图书馆就被导入了。这意味着您不需要使用诸如
import * from 'j2m';
But if you want to use a global variable without your IDE throwing errors, then you should add
但是如果你想使用一个全局变量而你的 IDE 不会抛出错误,那么你应该添加
declare var J2M: any;
with J2M
being the exported, global function from your library (for instance, for MomentJS, this variable is called moment
).
同J2M
是从资料库中导出,全局函数(例如,用于MomentJS,这个变量叫做moment
)。
When you use a definition file, it just tells the CLI to automatically fetch the JS library, and gives you IDE auto-completion. With this solution, you don't have auto-completion, and you explicitly tells the CLI where to fetch the library.
当您使用定义文件时,它只是告诉 CLI 自动获取 JS 库,并为您提供 IDE 自动完成功能。使用此解决方案,您没有自动完成功能,并且您明确告诉 CLI 从何处获取库。