1

hello how do you access variables in bundle.js?

I am trying to make a client side javascript and play around with variables and functions but am having trouble calling them in index.html, chrome-console.

I use browserify to bundle my script.js into bundle.js (which helps me with 'require' which the browser does not recognize), however when I try to access variables or functions defined in the script.js, now bundle.js I get e.g. Uncaught ReferenceError: xx is not defined

Any help? Or am I not allowed to use node packages on client side html/scripts?

edit: did a bit of googling and came upon this guy who says I should use XHR / AJAX "require" is not defined error- javascript

edit2: window.xx = xx seems to be a temporary solution

3
  • Have you imported your script using a script tag in your html? for example: <script src="bundle.js"></script> Commented Oct 17, 2019 at 13:53
  • yup I have imported my script! Commented Oct 17, 2019 at 13:55
  • I think this is a duplicate but the question is rather unclear. Commented Oct 17, 2019 at 13:56

1 Answer 1

0

Correct me if I'm wrong, because I have not used Browserify (I've used other bundling/processing tools), but to my understanding, Browserify bundles up all the code from the original source file into a bundle.js file. Within that bundle.js is a scope that is not accessible from the outside (unless specifically exported perhaps, but that's another story).

So for example:

// source.js
var test = require('./some-file-with-an-empty-object.js');
// Pseudo code example of bundle.js
;(function(){
   var test = {};
})();

Because of this IIFE, the scope var test is limitted and not accessible to external scripts or window.

So in short, do what you need to do within your source file, not outside of it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.