Ash*_*ngh 5 typescript libphonenumber angular
我想在我的角度项目中使用 Typescript 使用 Google libphonenumber。我在互联网上搜索了很多东西,找到了很多东西,但找不到任何可以达到我目的的东西。
大多数可用内容都显示了 JavaScript 代码。如果我在打字稿中使用相同的代码,它会显示很多错误,例如“找不到名称要求”或“找不到模块”。请告诉我如何/在哪里/什么编写代码。
另外,请告诉我要安装哪个包,因为有很多 - libphonenumber、google-libphonenumber、angular-libphonenumber
在处理 CommonJS 库时,在 TypeScript 中,就像这个google-libphonenumber 一样,我想建议 2 种方法(经我测试,效果很好)。
最初,我想建议像这样从 NPM 安装:npm install --save google-libphonenumber.
然后,我们在这里使用它的两种方式:
直接导入就行
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
}
}
Run Code Online (Sandbox Code Playgroud)
您仍然可以打字稿打字的力量或只是使用现有的一个:npm install --save-dev @types/google-libphonenumber。
既然您说您使用的是 Angular,那么您可以声明刚刚安装的类型src/tsconfig.app.json(我使用的是 Angular 版本 7)。这是我做的一个例子:
{
...
"compilerOptions": {
...
"types": [
"google-libphonenumber"
]
},
...
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像往常一样导入它,以 Typescript“打字”方式如下:
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
}
}
Run Code Online (Sandbox Code Playgroud)