问题描述
我想在我的使用Typescript的角度项目中使用Google libphonenumber.我在互联网上搜索了很多东西,发现了很多东西,但是找不到任何可以满足我目的的东西.
大部分可用内容显示了JavaScript中的代码.如果我在打字稿中使用相同的代码,则会显示很多错误,例如找不到名称要求"或找不到模块".请告诉我如何/在何处/以何种方式编写代码.
另外,请告诉我要安装哪个软件包,因为有很多-libphonenumber,google-libphonenumber,angular-libphonenumber
I want to use Google libphonenumber in my angular project using Typescript. I have searched a lot on internet and found a lot of stuff but could not find anything that could serve my purpose.
Most of the content available shows the code in JavaScript. If I use the same code in typescript, it shows lot of error like 'cannot find name require' or 'module not found'. Please tell me how/where/what to write the code.
Also, plz tell me which package to install as there are many - libphonenumber, google-libphonenumber, angular-libphonenumber
推荐答案
在处理CommonJS库时,在TypeScript中,就像 google-libphonenumber 一样,我想提出两种解决方法(由我测试,效果很好).
when dealing with CommonJS libraries, in TypeScript just like this google-libphonenumber, I'd like to suggest 2 ways about it (Tested by me and works well).
我第一次建议从NPM安装,就像这样:npm install --save google-libphonenumber
.
First time I'd like to suggest to install from NPM just like this: npm install --save google-libphonenumber
.
然后在这里我们介绍两种使用方式:
Then here we go the 2 ways of using it:
只需直接导入
import libphonenumber from 'google-libphonenumber';
class Something {
constructor() {//Just example, you can chose any method
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
}
}
第二种方法
您仍然可以使用Typescript打字,也可以通过npm install --save-dev @types/google-libphonenumber
使用现有的打字稿.
2nd Method
You still can make the power of Typescript typing or just use the existing one by: npm install --save-dev @types/google-libphonenumber
.
由于您说过使用的是Angular,因此您可以声明键入刚刚安装在src/tsconfig.app.json
上(我使用的是Angular版本7).这是我做的一个例子:
Since you said that you using Angular, so you can declare that typing just installed at src/tsconfig.app.json
( I am using Angular Version 7 ). Here is an example I have made:
{
...
"compilerOptions": {
...
"types": [
"google-libphonenumber"
]
},
...
}
然后,您可以像平常一样以Typescript类型"的方式导入它,如下所示:
Then you can just import it like usual, in Typescript "typings" way like follow:
import { PhoneNumberUtil } from 'google-libphonenumber';
class Something {
constructor() {//Just example, you can chose any method
const phoneUtil: PhoneNumberUtil = PhoneNumberUtil.getInstance();
console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
}
}
这篇关于如何在Typescript中使用Google libphonenumber?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!