Missing module exports in IE11/Edge - javascript

I'm having trouble getting an npm module to work since it was changed to ES2015.
I have an ES2015 app that is bundled by browserify and transformed with babelify. I am trying to upgrade an npm module named credit-card for credit card validation, which was changed from ES5 to ES6 in the current version. The problem starts with IE11/Edge. The code works fine on Chrome. Here's how the module is imported in the transformed app (babel'd code):
var _this = this;
var _creditCard = require('credit-card');
var _creditCard2 = _interopRequireDefault(_creditCard);
Here's a piece of code calling it:
this.validateCreditCard = function () {
var ccNumber = _this.account_number_credit_card.value.replace(/\D/, '');
_this.creditCardValidation = {
accountHolder: _this.account_holder_credit_card.value.replace(/\W/g, '').length >= 2,
cvc: _this.account_cvc_credit_card.value.replace(/\D/g, '').length > 2,
accountNumber: _creditCard2.default.isValidCardNumber(ccNumber, _creditCard2.default.determineCardType(ccNumber, { allowPartial: true }))
};
return _underscore2.default.all(_underscore2.default.values(_this.creditCardValida tion));
};
Now on Chrome this works without a problem. On IE however, the exported functions of the credit card module are missing.
Here's a printscreen of a console log of the module in IE
And here's Chrome
It looks like defaults is completely missing in IE. Is this a known issue? Do any of you have encountered this problem before and can give me some hints? Any pointers on how I could investigate this issue to understand what is going wrong and how I could fix it?

Stepping through the require() in IE11 Debugger i found out that there was a problem with Object.assign being undefined in IE11. After some searching I found this thread. The answer in this thread worked out in the end. I needed to add polyfill to my browserify bundle and enable the "transform-es2015-classes" plugin with the opt loose: true (See this thread for code).

Related

Reason for node module #kenjiuno/msgreader error: MsgReader is not a constructor

I'm unable to get even the first lines of the example code from the relatively popular #kenjiuno/msgreader for parsing Outlook .msg files to work. I've installed the module with npm successfully, and my code is:
const fs = require('fs')
const MsgReader = require('#kenjiuno/msgreader')
const msgFileBuffer = fs.readFileSync('./test-email.msg')
const testMsg = new MsgReader(msgFileBuffer)
But I get the error: "MsgReader is not a constructor".
A quick console log of MsgReader returns { default: [Function: MsgReader] }. I also tried doing it as a function (no 'new' keyword) which also produced an error.
The only difference between my code and the example code is that they use import (import MsgReader from '#kenjiuno/msgreader') whereas I've used require, but presumably that couldn't make a difference?
Any ideas anyone?
I ended up changing the require statement to add ["default"] which fixed the issue:
const MsgReader = require('#kenjiuno/msgreader')["default"]
I looked at the library code and made a guess based on the export statement using that 'default' syntax. Is this issue something to do with commonJS or something? If anyone can explain this to me that would be great!

Why am I getting ".at" is not a function?

I know how to index an array with [] but I'm trying to display an item from an array based on its index using Array.at() method as described here MDN Docs - Array.at
But I get the following error:
Uncaught TypeError: arr1.at is not a function
I double-checked it, and everything is ok, however I don't know what's going wrong.
Here is my code:
const arr1 = [10, 20, 30, 40, 50];
const res = arr1.at(2);
console.log(res);
Note: This is different than the proposed duplicate of How to get value at a specific index of array In JavaScript?. That question is about methods for accessing an array, this question is why a new API for doing so is unavailable and how to rectify that.
If you get this message, whatever platform you're running the code on does not support the method yet. It's quite new - while the most recent versions of most browsers support it, anything before 2021 definitely won't. This method was only very recently signed off on (end of August 2021) and incorporated into the official specification, so it won't exist in older environments. Either upgrade your environment, or add a polyfill.
Per the proposal document, a "rough polyfill" that should be standards-compliant for most cases is:
function at(n) {
// ToInteger() abstract op
n = Math.trunc(n) || 0;
// Allow negative indexing from the end
if (n < 0) n += this.length;
// OOB access is guaranteed to return undefined
if (n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access
return this[n];
}
const TypedArray = Reflect.getPrototypeOf(Int8Array);
for (const C of [Array, String, TypedArray]) {
Object.defineProperty(C.prototype, "at",
{ value: at,
writable: true,
enumerable: false,
configurable: true });
}
Simply run that before trying to use .at, and you should be able to use it, even on older incompatible environments. You can also install this more exhaustive shim instead if you wish.
One option is to use the core-js library...
Modular standard library for JavaScript. Includes polyfills for
ECMAScript up to 2021: promises, symbols, collections, iterators,
typed arrays, many other features, ECMAScript proposals, some
cross-platform WHATWG / W3C features and proposals like URL. You can
load only required features or use it without global namespace
pollution.
First install it with npm or yarn:
npm install core-js
or
yarn add core-js
Then use it in your JS or TS project like this:
import 'core-js/features/array/at';
let arr = [];
arr.push(42);
console.log(arr.at(0));
Note that the code above only imports the at method for array. To import all polyfills or a subset:
// polyfill all `core-js` features, including early-stage proposals:
import "core-js";
// or:
import "core-js/features";
// polyfill all actual features - stable ES, web standards and stage 3 ES proposals:
import "core-js/actual";
// polyfill only stable features - ES and web standards:
import "core-js/stable";
// polyfill only stable ES features:
import "core-js/es";
If you're using node.js then please check the version of node.
It should be greater than 16.6.0. If not then update the node.js version.
Browser compatibility of Array.prototype.at()
The code is working fine in Stackoverflow code terminal. Your machine might not support the same due to JS versioning. The method is introduced recently.
I ran into this same issue when using Pipedream. I didn't realize that at() wasn't included in the NodeJS version they're using hinted at by Li Ki.
I implemented a similar solution proposed by Bjørnar Hvidsten; however, to get it to work in Pipedream, I simply added the following to the top of my NodeJS code.
import 'core-js'
const myArray = [1,2,3]
console.log(typeof myArray.at) // "function"
P.S. Referencing specific parts of core-js resulted in errors inside Pipedream, at least how I was trying to call it.

PptxGenjs writeFile() not working in IE11

While everything seems to work fine, when debugger hits pres.writeFile() function , i cant get the pptx at all. Mostly like a promise-base issue. Of course when testing with Chrome everything works as expetexted. Anyone face any similar issue before? Any suggestions? What's wrong with IE11?
var pres = new pptxgen();
function fetch_data(el) {
$.ajax({
url:`${document.querySelector('.off-to-see-the-wizard > .route').innerHTML}`,
contentType:"application/json",
dataType:"json",
success:function(response){
if(response)
{
var data=JSON.parse(response);
createPresentation(data,el);
}
else{
console.log(response)
}
},
error:function(err){
console.log(err);
}
})
}
function createPresentation(data){
var second_image="image/base64 ...."
var main_image="image/jpg;base64 ..."
function createMasterSlide(pres){
pres.defineSlideMaster({
title:'MASTER_SLIDE',
bkgd: 'FFFFFF',
objects:[
{'text':{text:`Test ${data._gateDescript} review`,options:{color:'000000',x:4.7,y:6.77,h:0.46,w:3.63, fontSize:14}}},
{'image':{x:0.3,y:6.47,w:1.14,h:0.83,data:second_image}}
],
slideNumber: { x:9.11, y:6.77 ,w:0.43 ,h:0.42}
})
}
function createMainSlide(pres){
pres.author="Team";
pres.layout='LAYOUT_4x3';
let main_slide=pres.addSlide();
main_slide.addImage({data:main_image, w:10, h:7.5})
main_slide.addText(`Project ID: ${data._p.Id}\nProject Name: ${data._p.Name}`, {color:'D55C00' ,x:0.47, y:3.56, w:5.0, h:0.7, fontSize:24})
main_slide.addText(`Review: Test ${data._gateDescript} \nDate: ${Date.now()} `)
}
createMasterSlide(pres);
createMainSlide(pres);
pres.writeFile('Presentation.pptx');
}
Quick Update
Error :
Please see image attached. Error
Ι get to know that jszip has an issue with ie11
To be specific pptxgenjs make use of jszip , that runs generateInternalStream. In the scope of this function something breaks out. Any clues?
Which version of jszip are you using? It seems that pptxgenjs#3.1.1 uses jszip v3.2.1 for default.
I found some have the same error when using jszip version 3.2.x in IE and Edge. You could refer to this thread. The last version not having this problem is 3.1.5. You could try with jszip version 3.1.x.
Quick update for your reference .
The issue was finally resolved by installing jszip 3.1.5 version.
Its stable and functionally using IE11.
So you should install this specific version
npm install jszip#3.1.5 --save
Then please navigate to node modules , get to copy all jszip node module.
Navigate back to pptxgenjs node module. Navigate into pptxgenjs--->node_modules and overwrite jszip with the version you have installed and copied previously.
So pptxgenjs lib would use jszip 3.1.5 version .
Issue resolved.
Thanks everyone :)

Why am I getting a 'no-unused-vars' warning in a for...of loop and how do I fix it?

I'm working on a React app created with Create React App. In every for...of loop, I get this weird 'no-unused-vars' warning pointing to the variable I have instantiated in the for statement.
ESLint tells me my variable is not used, but it is actually used.
Does anybody else get a similar warning? Is it an ESLint bug or am I doing something wrong here?
This is not a big issue, but it is annoying.
Thanks for your help.
for (let track of tracks) {
let chords = RavelFormatter.splitEntries(track.pitches)
for (let chord of chords) {
var n = chord.split(':')
total += n.length
}
}
Console output
Line 13: 'track' is defined but never used no-unused-vars
Line 15: 'chord' is defined but never used no-unused-vars
Please upgrade the babel-eslint package to version 10.0.3.
This will most likely fix those false-positives where vars are used inside loops and wrongly reported as unused.
See issue 12117, which is related to a specific version of ESLint. You can revert your ESLint version back to v6.1.0 to resolve this.
Upgrade to eslint 6.8.0 and babel-eslint 10.1.0.
This is a known issue with babel-eslint and is related to the eslint-scope version used. It looks like it started in eslint 6.1.0.
Just upgrade your packages to (at least):
"babel-eslint": 10.1.0,
"eslint": 6.8.0
You can view the Github Issues here:
https://github.com/eslint/eslint/issues/12117
https://github.com/babel/babel-eslint/issues/791
I was able to fix it by using this.
let track = null;
for (track of tracks) {
let chords = RavelFormatter.splitEntries(track.pitches)
for (let chord of chords) {
var n = chord.split(':')
total += n.length
}
}

How to make Javascript code run in Phoenix?

So I am having a hard time making Javascript written in app.js actually work. This is what I have done so far:
First thing I did was write the code into the app.js file and hope it would work.
App.js
import "deps/phoenix_html/web/static/js/phoenix_html"
const selectSort = document.getElementById("sort");
console.log("Herp");
const sortEntities = () => {
const sortvalue = selectSort.value;
const entities = document.querySelectorAll(".entitiy");
const sortedEntities = entities.sort((a, b) =>
a.querySelector(`.${sortvalue}`).textContent > a.querySelector(`.${sortvalue}`).textContent);
document.querySelector(".entitiy-list").innerHTML = sortedEntities;
};
selectSort.addEventListener("onChange", sortEntities);
Now I tried accessing the selectSort variable through console but I get undefined. I discovered that the app.js is never loaded in since I run windows and it could be fixed by adding another line in the autoRequire.
brunch-config.js
<---SNIPPET-->
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"] <-- The line added
}
},
<---SNIPPET-->
Now that the app.js file finally loads properly I get an error with the phoenix_html import.
Error
Uncaught Error: Cannot find module "deps/phoenix_html/web/static/js/phoenix_html" from "web/static/js/app"
Even if I remove the import the variable will still not load properly when i type it into the console and the code never executes, while console.log message is executed. What am I missing? If I try write the code in the console window it works fine.
The project itself is quite old, probably from like November, so i might not be running the newest "phoenix template". Not sure if there are some known issue to this related there, i tried looking around. I even have "Programming Phoenix" but there wasn't much about making Javascript run there.
My project used Phoenix 1.0 which had known issues with Windows and making Javascript execute properly. I upgraded to 1.1.2 and now everything works fine.

Categories