Reputation: 1506
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 require
's (./logger and ./includes/functions). The app.js looks like this:
require('./logger');
require('./includes/functions');
document.write( welcomeTitle );
welcomeTitle
is the variable declared in ./includes/functions
:
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 welcomeTitle
variable before it's required:
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
__webpack_require__(2);
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 welcomeTitle
variable if I'm requiring functions.js, where this variable is declared?
Upvotes: 1
Views: 818
Reputation: 1640
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;
Upvotes: 4