使用“ google-libphonenumber”中的PhoneNumberFormat无效

时间:2019-12-04 15:29:29

标签: javascript ecmascript-6

我想使用google-libphonenumber库格式化电话号码。我不想使用Require,而是想使用ES6导入。但这似乎不起作用

import { PhoneNumberUtil, PhoneNumberFormat } from 'google-libphonenumber'

const phoneUtil = PhoneNumberUtil.getInstance()
let number = phoneUtil.parse(target.value, 'US') . //works
let valid = phoneUtil.isValidNumber(number) .   //works
console.log(phoneUtil.format(phone, PhoneNumberFormat.INTERNATIONAL)) //does not work

我后来尝试使用require

const PNF = require('google-libphonenumber').PhoneNumberFormat

console.log(phoneUtil.format(phone, PNF.INTERNATIONAL))

这也会产生错误

TypeError: a.getNationalNumber is not a function
i18n.phonenumbers.PhoneNumberUtil.format
node_modules/google-libphonenumber/dist/browser/libphonenumber.js:5435

1 个答案:

答案 0 :(得分:2)

在您的情况下,您似乎通过了电话而不是电话号码

此函数需要一个“ PhoneNumber”对象

import {
  PhoneNumberUtil,
  // using PNF alias to follow along with documentaion
  PhoneNumberFormat as PNF
} from 'google-libphonenumber';

  // grab your instance
  const phoneUtil = PhoneNumberUtil.getInstance();

  // here we are parse our number into that object
  const number = phoneUtil.parse('121231234', 'ZA');

  console.log(phoneUtil.isPossibleNumber(number));
  console.log(phoneUtil.format(number, PNF.INTERNATIONAL));