我想使用 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
在您的情况下,您似乎通过了电话而不是号码
此函数需要一个“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));
我发现我必须做:
import { default as libphonenumber } from "google-libphonenumber";
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
const number = phoneUtil.parse(input, countryCode);
const numberE164 = phoneUtil.format(number, libphonenumber.PhoneNumberFormat.E164);
如此处回答:https://github.com/ruimarinho/google-libphonenumber/issues/17#issuecomment-121340131