使用“google-libphonenumber”中的 PhoneNumberFormat 不起作用

Ki*_*aya 1 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
Run Code Online (Sandbox Code Playgroud)

我后来尝试使用 require

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

console.log(phoneUtil.format(phone, PNF.INTERNATIONAL))
Run Code Online (Sandbox Code Playgroud)

这也给出了错误

TypeError: a.getNationalNumber is not a function
i18n.phonenumbers.PhoneNumberUtil.format
node_modules/google-libphonenumber/dist/browser/libphonenumber.js:5435
Run Code Online (Sandbox Code Playgroud)

Luk*_*sen 7

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

此函数需要一个“电话号码”对象

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));
Run Code Online (Sandbox Code Playgroud)