0

I have 2 js files that I want to compile in Laravel Mix and be able to access variables.

mix.js([
    'resources/js/dashboard/sidebar.js',
    'resources/js/dashboard/app.js',
]).'public/js/app.js');

I want to be able to separate sidebar so that I don't write everything in 1 file.

In my app.js,

"use strict";
$(function(){
    console.log("B");
    console.log(Sidebar());
})

And in my sidebar.js

"use strict";
console.log("A");

var Sidebar = function() {
   console.log("C")
   // setup of the sidebar
});

However, I keep receiving:

jQuery.Deferred exception: Sidebar is not defined ReferenceError: Sidebar is not defined Uncaught ReferenceError: Sidebar is not defined

If I check the console.log dummy things, I get:

A
B
jQuery.Deferred exception: Sidebar is not defined ReferenceError: Sidebar is not defined
Uncaught ReferenceError: Sidebar is not defined

and never "C"

I also tried to remove sidebar.js from Laravel Mix part and do require('./sidebar.js) but same issue persists. I also tried changing swapping them mix.js


In the compiled file, I have in this order:

$(function () {
    Sidebar();
});

"use strict";
Sidebar = function () { ... }
senty
  • 12,385
  • 28
  • 130
  • 260
  • Did you try setting `Sidebar()` in window object ? – Bharath Apr 24 '19 at 17:16
  • Have you tried looking inside `public/js/app.js` file to see what the compiled result is? Might be a helpful clue. – Bryan Apr 24 '19 at 17:24
  • @Bharath If I try window.sidebar, it works indeed; but is this a good way to go? How about utilising `module.exports = Sidebar;` in the sidebar.js file? – senty Apr 24 '19 at 17:24
  • Ah, I see. It's a scope issue. @Bharath got it right. – Bryan Apr 24 '19 at 17:28
  • @Bryan actually, the order in compiled file is wrong, but would it cause an issue? Is using `window.` good approach? I'd prefer to access it just with `Sidebar` rather than `window.Sidebar` – senty Apr 24 '19 at 17:31
  • The error says `Sidebar()` is not defined. So giving `Sidebar()` in window object, would make it available globally (JS Clousre). Since you are already including `sidebar.js`, is it necessary to use `module.export` ? – Bharath Apr 24 '19 at 17:38
  • It's kind of subjective what's good or bad. This question has some answers that might help you: https://stackoverflow.com/questions/1841916/how-to-avoid-global-variables-in-javascript – Bryan Apr 24 '19 at 17:39
  • I kind of understand the issue, thanks guys – senty Apr 24 '19 at 17:41

0 Answers0