我最近刚刚开始将 Webpack 作为 future jQuery 插件的模块加载器,但在尝试将各个原型(prototype)函数分离到单独的文件中时遇到了问题。 Webpack 似乎将原型(prototype)函数导入到单独的 IFFE 中,这反过来又给我一个控制台错误。
我做错了什么根本性的事情吗?
示例代码:(运行 webpack 之前)
app.js
function() {
var Cars = function(color, doors, year, make) {
this.color = color;
this.doors = doors;
this.year = year;
this.make = make;
}
require('./imports/module1.js');
var Audi = new Cars("red", 5, 2001, "Audi");
Audi.listing();
})();
module1.js
// Module 1
console.log("Module 1");
Cars.prototype.listing = function() {
console.log(this.year + ", " + this.color + ", " + this.make + ", with " + this.doors + " doors");
}
WEBPACK 片段
/******/ ([
/* 0 */
/***/ (function(module, exports) {
// Module 1
console.log("Module 1");
Cars.prototype.listing = function() {
console.log(this.year + ", " + this.color + ", " + this.make + ", with " + this.doors + " doors");
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
(function() {
var Cars = function(color, doors, year, make) {
this.color = color;
this.doors = doors;
this.year = year;
this.make = make;
}
__webpack_require__(0);
var Audi = new Cars("red", 5, 2001, "Audi");
Audi.listing();
})();
/***/ })
/******/ ]);
控制台错误
Uncaught ReferenceError: Cars is not defined
at Object.make.color (module1.js:4)
at __webpack_require__ (bootstrap 91cca6f…:19)
at app.js:12
at Object.<anonymous> (app.js:20)
at __webpack_require__ (bootstrap 91cca6f…:19)
at bootstrap 91cca6f…:65
at bootstrap 91cca6f…:65
最佳答案
代码中的一些问题:
您的
module1
不是一个真正的模块,它依赖于未声明的变量Car
。这就是报告错误的原因。此外,
module1
尝试对Cart
产生副作用(也就是在 Car 的原型(prototype)上添加一个属性),这不是一个好的做法。产生副作用是可以的,但最好在需要时显式设置它,而不是通过模块加载。在
Cars
模块中,最好将require
部分视为静态部分,而不是采取某种效果的方法。 (参见此引用:http://webpack.github.io/docs/code-splitting.html#es6-modules)
建议的改进和修复:
// module 1
module.exports = {
list: function list() { /* .... */ }
}
// Cars
// require, no effect;
var module1 = require('./module1')
function Cars() {
// code
}
// Take effect. via extending. I used underscore, you can use whatever extending methods such as $.extend
_.extend(Cars.prototype, module1}
//....other code
实际上模块中不需要IFFE,你可以去掉它。
关于javascript - WEBPACK - 我如何需要原型(prototype)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42468768/