erol_smsr erol_smsr - 8 months ago 49
Javascript Question

Can't get global variable from other JS file in main JS file with webpack

I'm learning Webpack and like the idea a lot, but I just don't get this issue I have. I have an app.js file, which has two

's (./logger and ./includes/functions). The app.js looks like this:


document.write( welcomeTitle );

is the variable declared in

var welcomeTitle = "Hello World!";

But I get the following error when I run this:
bundle.js:50 Uncaught ReferenceError: welcomeTitle is not defined(…)
. The bundle.js file references to the
variable before it's required:

/* 0 */
/***/ function(module, exports, __webpack_require__) {


document.write( welcomeTitle );

/***/ },
/* 1 */
/***/ function(module, exports) {

console.log('logger.js is now loaded...');

/***/ },
/* 2 */
/***/ function(module, exports) {

var welcomeTitle = "Hello World!";

Why can't I access the
variable if I'm requiring functions.js, where this variable is declared?

Answer Source

Add module.exports to the bottom of your functions file ./includes/functions.js and set welcomeTitle as a property on exports`.

var welcomeTitle = 'Hello World';

module.exports.welcomeTitle = welcomeTitle;

Then in the file that you want to access welcomeTitle in do:

var functions = require('./includes/functions');
var welcomeTitle = functions.welcomeTitle;