在Angular 5中,如何导入没有@types的NPM模块 [英] In Angular 5, how can I import NPM modules with no @types

查看:233
本文介绍了在Angular 5中,如何导入没有@types的NPM模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Angular 5,从angular-cli开始一个项目.在这个项目中,我想使用一个NPM模块:J2M( https://github.com/kylefarris/J2M ),所以我上网查看了这两个命令:

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 :

npm install j2m --save
npm install @types/j2m --save-dev

不幸的是,@ types/j2m根本不存在. 所以我试图找到一种定义自己的类型的方法,但没有成功...

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...

我正在使用此代码:

import * as J2M from "j2m";
...
console.log(J2M.toM(value));

但是,根据我在网上找到的示例,"j2m"无法识别,或者"toM"不是函数...

But either "j2m" is not recognized, or "toM" is not a function, based on the samples I found online...

那么,导入此模块的正确方法是什么?

So, what's the proper way to import this module?

谢谢

推荐答案

您需要将脚本添加到您的angular-cli.json文件中.

You need to add the scripts into your angular-cli.json file.

scripts属性下,添加

'../node_modules/path/to/minified/js.js'

如果需要样式,则还必须将其添加到同一文件的styles属性下.

If a style is required, you must also add it under your styles property, in the same file.

完成此操作后,您的库将被导入.这意味着您不需要使用诸如

Once you did that, your library is imported. This means you don't need to use such things as

import * from 'j2m';

但是,如果您想使用全局变量而不会导致IDE抛出错误,则应该添加

But if you want to use a global variable without your IDE throwing errors, then you should add

declare var J2M: any;

,其中J2M是库中导出的全局函数(例如,对于MomentJS,此变量称为moment).

with J2M being the exported, global function from your library (for instance, for MomentJS, this variable is called moment).

使用定义文件时,它只是告诉CLI自动获取JS库,并为您提供IDE自动完成功能.使用此解决方案,您无需自动完成,并且可以明确告诉CLI从何处获取库.

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.

这篇关于在Angular 5中,如何导入没有@types的NPM模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆