使用webpack

时间:2016-11-28 23:34:28

标签: javascript webpack

我正在学习Webpack并且很喜欢这个想法,但我只是没有得到这个问题。我有一个app.js文件,它有两个require(./logger和./includes/functions)。 app.js看起来像这样:

require('./logger');
require('./includes/functions');

document.write( welcomeTitle );

welcomeTitle./includes/functions中声明的变量:

var welcomeTitle = "Hello World!";

但是当我运行此命令时出现以下错误:bundle.js:50 Uncaught ReferenceError: welcomeTitle is not defined(…)。 bundle.js文件在需要之前引用welcomeTitle变量:

/* 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!";

为什么我不能访问welcomeTitle变量,如果我需要function.js,声明这个变量?

1 个答案:

答案 0 :(得分:4)

module.exports添加到您的函数文件./includes/functions.js的底部,并将welcomeTitle设置为exports`上的属性。

var welcomeTitle = 'Hello World';

module.exports.welcomeTitle = welcomeTitle;

然后在您要在do:

中访问welcomeTitle的文件中
var functions = require('./includes/functions');
var welcomeTitle = functions.welcomeTitle;