I am working on an Angular 2 application with Webpack.
I am implementing a pipe in Angular 2 to format phone number using google-libphonenumber. Everything is working as expected. I am not very knowledgeable on how require works i.e., it is as simple as using an existing JS function or loads a library doing an expensive operation. So I'm not sure if I have to define PNF
and phoneUtil
in the example below, outside the transform
function in pipe.
export class PhonePipe implements PipeTransform {
transform(value: string) {
let PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
let phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Add a leading '+' sign if not available. Assumption is all numbers contain country code prefixed.
let newValue = value.length > 0 && value.charAt(0) != "+" ? "+" + value : value;
// Format the number.
let parsedPhoneObj = phoneUtil.parse(newValue, 'US');
console.log(parsedPhoneObj);
return phoneUtil.format(parsedPhoneObj, PNF.INTERNATIONAL);
}
}
Will appreciate any suggestions. My goal is optimize the application performance.
I would do:
import * as libphonenumber from 'google-libphonenumber';
export class PhonePipe implements PipeTransform {
transform(value: string) {
let PNF = libphonenumber.PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
let phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
// Add a leading '+' sign if not available. Assumption is all numbers contain country code prefixed.
let newValue = value.length > 0 && value.charAt(0) != "+" ? "+" + value : value;
// Format the number.
let parsedPhoneObj = phoneUtil.parse(newValue, 'US');
return phoneUtil.format(parsedPhoneObj, PNF.INTERNATIONAL);
}
}
You don't really use require
with typescript, instead you can use import as showed. This also gives you 1 import rather than 2 like you had before.