WEBPACK - 我如何需要原型函数?

WEBPACK - How do i require prototype functions?

我最近才开始研究 Webpack 作为未来 jQuery 插件的模块加载器,但我 运行 在尝试时遇到了问题将单独的原型函数分隔在单独的文件中。 Webpack 似乎将原型函数导入到单独的 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

您的代码中存在一些问题:

  1. 您的 module1 不是真正的模块,它依赖于未声明的变量 Car。这就是报错的原因。

  2. 此外,module1 试图对 Cart 产生副作用(也就是在 Car 的原型上再添加一个属性),这不是一个好的做法。产生副作用是可以的,但最好在需要时明确设置它,而不是通过模块加载。

  3. 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,你可以去掉它。