Uncaught ReferenceError when adding JS to app.js in Laravel

381 Views Asked by At

I have some browser sniffer code using the function detect.js. It works fine when not added to my project. Still, when I try to compile the JavaScript and add it to app.js, I get an error in the console at the first line below, refreshing the browser and detecting the browser version.

Uncaught ReferenceError: forEach is not defined.

// Each Utility
var each = forEach = function (obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
        obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
        for (var i = 0, l = obj.length; i < l; i++) {
            iterator.call(context, obj[i], i, obj);
        }
    } else {
        for (var key in obj) {
            if (_.has(obj, key)) {
                iterator.call(context, obj[key], key, obj);
            }
        }
    }
};

It seems like compiling the JavaScript is doing something to it. Any suggestions?

1

There are 1 best solutions below

1
Karl Hill On

If I use the detect-browser package.

npm i detect-browser

Then add the following to my app.js...

const { detect } = require('detect-browser');
const browser = detect();

try {
    // handle the case where we don't detect the browser
    if (browser) {
        console.log(browser.name);
        console.log(browser.version);
        console.log(browser.os);
    } else {
        console.log('no browser');
    }
} catch (e) {
    console.log(e);
}

And issue an npm run prod...

When I pull up the page, I get the following in my console (no errors).

enter image description here