0

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.

TechCrunch
  • 2,924
  • 5
  • 45
  • 79
  • I've marked that as duplicate because basicly what you are asking is how to use a 3rd party lib with angular – eko May 26 '17 at 05:10
  • Not sure why this would be a duplicate. My code is working already. All I want to know is if should keep the require outside or not to optimize the code. – TechCrunch May 26 '17 at 05:13
  • Oh I didn't realize that the code was working, my bad. I'm removing the dupe. Still if you checked the link it is giving you the info on how to use 3rd party libs in your project.. – eko May 26 '17 at 05:14
  • where does this `require` come from? what do you use - `angular-cli`, `systemjs`? – Max Koretskyi May 26 '17 at 05:34
  • Webpack. I included `google-libphonenumber` in `vendor.ts` – TechCrunch May 26 '17 at 05:36

1 Answers1

2

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.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175