Is libphonenumber-js compatible with Angular's buildOptimizer option? - javascript

I'm trying to implement libphonenumber-js in my hybrid angularjs and Angular 7.2.2 project. It works fine in JIT (ng serve) but it gives errors when I enable buildOptimizer and optimize in angular.json.
If I enable only one of the above, it works fine as well.
I have no errors during the build, but when I open the form on the site I have the following in my console.
angular.js.pre-build-optimizer.js:14961 TypeError: (0 , r.default) is not a function
at MfjL.e.default (isValidNumberForRegion.js.pre-build-optimizer.js:37)
at e.isValidNumberForRegion (phone-utils.service.ts:32)
at O (my-account-data-controller.js.pre-build-optimizer.js:48)
at xt (my-account-data-controller.js.pre-build-optimizer.js:57)
at Object.invoke (angular.js.pre-build-optimizer.js:5117)
at O.instance (angular.js.pre-build-optimizer.js:11139)
at it (angular.js.pre-build-optimizer.js:10002)
at angular.js.pre-build-optimizer.js:9311
at angular.js.pre-build-optimizer.js:9176
at Object.link (angular.js.pre-build-optimizer.js:28821)
We use ng upgrade (https://angular.io/guide/upgrade) in our site.
In the chrome debugger, when I click on angular.js.pre-build-optimizer.js:14961, I get to
// Support: IE 9 only
// console methods don't inherit from Function.prototype in IE 9 so we can't
// call `logFn.apply(console, args)` directly.
return Function.prototype.apply.call(logFn, console, args);
When I click on isValidNumberForRegion.js.pre-build-optimizer.js:37, this is the code:
// `parse` extracts phone numbers from raw text,
// therefore it will cut off all "garbage" characters,
// while this `validate` function needs to verify
// that the phone number contains no "garbage"
// therefore the explicit `isViablePhoneNumber` check.
var input = void 0;
if ((0, _isViablePhoneNumber2.default)(number)) {
input = (0, _parse_2.default)(number, { defaultCountry: country }, metadata);
} else {
input = {};
}
The function that is not found being (0, _isViablePhoneNumber2.default)(number).
I would really like to be able to use both optimize and buildOptimizer since it is a huge app and this really improves performance. Any idea how to debug that ?
EDIT: This may be related https://github.com/angular/angular-cli/issues/11439

Updating the library to version 1.7.6 and using the new functions fixed the issue.

Related

Arrow function "expression expected" syntax error

I want to transform this code:
var formatQuoteAmount = function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD');
};
var quoteAmounts = res.transactions.map(formatQuoteAmount);
into an anonymous arrow function. I've written this:
var quoteAmounts = res.transactions.map(tx => Currency.toSmallestSubunit(tx.usd, 'USD'));
I get expression expected syntax error at the arrow. I looked up the default syntax here and seems like the syntax of my code is correct. Any ideas what the problem might be?
I have it working with this syntax:
var quoteAmounts = res.transactions.map(function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD')
});
but I want to make it a one-liner, with an arrow-function.
Running on node v5.3.0
I had the error expression expected reported by Webstorm when editing a Node.js program. In this case the solution is to set the language version to a version that supports this feature.
The following is what i did that work for me.
(1) I change the JavaScript language option to ECMAScript 6 as show in the selected answer by #Joe23
(2) I close the Webstorm project/application.
(3) Navigate to the project folder and delete the .idea folder in it. I believe this is the folder webstorm generated to keep information about the project/application.
(4) I reopen my project in webstorm and the errors are gone.
Arrow functions are available by default on the latest versions of node and other javascript runtimes. You need to enable support for them only if you're dealing with a really old runtime (0.12 and earlier if I recall correctly) in which case you need to add the "--harmony" flag when you start the node process.

Cordova - Deprecated attempt to access property 'userAgent' on a non-Navigator object

I'm trying to get my Cordova iPhone app working in iOS 8.1
Working fine in 7, since 8 I'm getting the following error:
Deprecated attempt to access property 'userAgent' on a non-Navigator object.
This is breaking the rendering of the app in page so I need a fix. I've taken a look at the various proposed solutions around the web but none seem to work.
Interestingly the error is coming from the JS retrieved from "https://maps.gstatic.com/maps-api-v3/api/js/17/17/main.js". --- perhaps part of the Google Maps API I'm trying to use?
Any help on the matter would be amazing!
Many thanks
Chris
Which cordova version are you using?
That should be fixed now in the latest version, but if you don't want to update the project, you can change replaceNavigator function to be like this on the cordova.js file (the whole else is new)
function replaceNavigator(origNavigator) {
var CordovaNavigator = function() {};
CordovaNavigator.prototype = origNavigator;
var newNavigator = new CordovaNavigator();
// This work-around really only applies to new APIs that are newer than Function.bind.
// Without it, APIs such as getGamepads() break.
if (CordovaNavigator.bind) {
for (var key in origNavigator) {
if (typeof origNavigator[key] == 'function') {
newNavigator[key] = origNavigator[key].bind(origNavigator);
} else {
(function(k) {
Object.defineProperty(newNavigator, k, {
get: function() {
return origNavigator[k];
},
configurable: true,
enumerable: true
});
})(key);
}
}
}
return newNavigator;
}
it looks like a known issue in cordova that can be fixed by updating your cordova version (as well as plugins?)
from Cordova Jira
If you want to get the fix simply do the following:
Clone the cordova-js (Version 3.7)
Grunt the git, this will create all the native js files.
Replace the cordova.js in your platform_www folder

In Appcelerator Titanium How can I disable javascript code optimization to make debugging easier?

I'm working with an iOS targeted app built using Titanium (with Alloy); I want to be able to turn off the Javascript code optimization within Titanium Studio, but cannot locate anything by Googling, nor searching SO. When Titanium compiles it produces optimized javascript files...which makes interactive debugging difficult because in many cases it combines several lines of clean, readable code into a single line... which makes stepping into the code with the debugger difficult.
For example:
this...
if(Array.isArray(detailItemArray)){
//term-item.detail-items
for(var z=0;z<detailItemArray.length;z++){
if(z===0){
//first item in detail-item array gets a title pre-pended to it
// title is optional
if(_.isString(termItemArray[y].title)){
htmlArray.push(html.termItem(termItemArray[y].title,html.processStyle(detailItemArray[z]['style'],detailItemArray[z]['detail'])));
} else{
htmlArray.push(html.processStyle(detailItemArray[z]['style'],detailItemArray[z]['detail']));
}
} else {
//process style if available, then add to the array buffer
htmlArray.push(html.processStyle(detailItemArray[z]['style'],detailItemArray[z]['detail']));
}
}
} else {
//when detailArray is not an array (sometimes it is -- see if statement above)
//the title is optional
if(_.isString(termItemArray[y].title)){
htmlArray.push(html.termItem(termItemArray[y].title,detailItemArray['detail']));
} else {
htmlArray.push(html.termItemNoTitle(html.processStyle(detailItemArray['style'],detailItemArray['detail'])));
}
}
turns into this...a single line...
if (Array.isArray(detailItemArray)) for (var z = 0; detailItemArray.length > z; z++) 0 === z ? _.isString(termItemArray[y].title) ? htmlArray.push(html.termItem(termItemArray[y].title, html.processStyle(detailItemArray[z]["style"], detailItemArray[z]["detail"]))) : htmlArray.push(html.processStyle(detailItemArray[z]["style"], detailItemArray[z]["detail"])) : htmlArray.push(html.processStyle(detailItemArray[z]["style"], detailItemArray[z]["detail"])); else _.isString(termItemArray[y].title) ? htmlArray.push(html.termItem(termItemArray[y].title, detailItemArray["detail"])) : htmlArray.push(html.termItemNoTitle(html.processStyle(detailItemArray["style"], detailItemArray["detail"])));
using Titanium Studio v3.2.3.201404181442
Any ideas if there is a setting that can temporarily disable this behavior so interactive debugging is easier?
Thanks in advance.
--Scott
EDIT: A suggestion from a co-worker was to sprinkle some log statements in the code (like right after the "for" statements; and sure enough this prevented the optimizer from in-lining the code. Not exactly how I wanted to go about it, but, at least got me moving forward. Would still like to find a way to turn down the JS optimizer level or off.
Try titanium build -p ios --skip-js-minify.
From titanium build --help:
Build Flags:
--legacy build using the old Python-based builder.py; deprecated
--skip-js-minify bypasses JavaScript minification; simulator builds are never minified; only
supported for Android and iOS [default: false]
-b, --build-only only perform the build; if true, does not install or run the app
-f, --force force a full rebuild

Enable/Disable debug code dynamically

I'm writing a decent sized JavaScript animation library, that I would like to include debugging code in. I could easily do a check :
if(myLib.debugger){
console.warn('warning message');
}
However if this runs a couple thousand times a second, it would eventually cause performance issues. Add in a few more checks throughout the code and the effect will be even more noticeable.
What I'm wondering is if it would be possible to check onload if the debugger should be enabled, and if so... turn something like this:
//debugger if(!this.name) console.warn('No name provided');
into:
if(!this.name) console.warn('No name provided');
Leaving the code commented if its not enabled, and uncommenting it if it is, thus removing any possible performance issues. Could this be done somehow with a regular expression on the entire script if loaded in through ajax? I'm trying to avoid the need for 2 versions of the same code, lib.dbug.js and a lib.js.
Cross browser compatibility is not of great importance for this (I'm really only worried about new browsers), I see it as nice to have item. If its possible however, it would be a great thing to have.
Any insight would be greatly appreciated.
The simplest way to do this would be to check if the debugger should be disabled and if so, replace it with a mock object that does nothing at the very start of your script:
if (!myLib.debugger) {
window.console = (function () {
var newConsole = {};
var key;
for (key in window.console) {
if (typeof window.console[key] === 'function') {
newConsole[key] = function () {};
}
}
return newConsole;
}());
}
The overhead of this approach should be negligible.
If this is a JavaScript library... then I'd expect as a 3rd party developer that I could download/use 2 versions. The production version (no debug, AND minimized). If I wanted to debug, I would point to the debug version of the library instead.
e.g.
<script src="foo-lib-min.js"></script>
<!-- swap to this for debugging <script src="foo-lib-full.js"></script>-->

Javascript Build Tools To Toggle Urls/Variables Between Production/Deployment

I am beginning my first big javascript project! I had a question about deployment. I am using ajax calls to a webservice. To set this up I have a static JS file with code like:
var API_URL_ROOT = 'http://api.example.com/';
var IN_DEVELOPMENT = True;
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)
I am using python/fabric to deploy. I was wondering if there were any prebuilt tools for handling the static analysis/manipulation of the javascript files., Right now it leaves toggling up to the commiters
I was planning on a deployment process like:
issue deploy command
"build" JS, by setting all values to production values (ie. IN_DEVELOPMENT = False)
Minify JS
Deploy code to production servers
I was thinking of just using sed or something to do the IN_DEVELPMENT = False replacement. I have looked at some of the popular minification tools and none seem to offer this sort of functionality.
I would assume that this is a pretty common problem for applications. How is it usually handled? Any help would be appreciated. Thank you
I recently read an article on hackernews from mozilla:
In the Mozilla Persona code base, we frequently expose difficult to
test private functions to the public interface, clearly marking the
extra functions as part of a test API. While other developers are
still able to call these private functions, the author’s intentions
are clear.
...
publicFunction: function() {
return "publicFunction can be invoked externally but "
+ privateFunction();
}
// BEGIN TESTING API
,
privateFunction: privateFunction
// END TESTING API
};
// privateFunction is now accessible via the TESTING API
function privateFunction() {
...
Code between the // BEGIN TESTING API and //END TESTING API
pseudo-markers can be removed for production during the build process.
So other companies are definitely doing this. Are there premade tools to facilitate the JS build proccess that can remove this code? I glanced at a number of their projects on github and didn't see any. Thank you
We are using dojo
And in dojo you can use conditional exclusions for the build version of your js in order to exclude parts of your code that you would not want in your build js. Hope this helps.
eg:
var API_URL_ROOT = 'http://api.example.com/';
//>>excludeStart("dev",!pragmas.dev);
var IN_DEVELOPMENT = True;
//>>excludeEnd("dev");
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)

Categories

Resources