WEBPACK - 我如何需要原型功能?

时间:2017-02-26 12:52:59

标签: javascript webpack prototype webpack-2

我刚刚开始将 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 snippit

/******/ ([
/* 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 个答案:

答案 0 :(得分:1)

代码中的一些问题:

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

  2. 同样module1尝试对Cart产生副作用(也就是在Car&#39的原型上添加一个属性),这不是一个好习惯。可以产生副作用,但最好在需要时明确设置,而不是通过模块加载。

  3. Cars模块中,最好将require部分视为静态部分,而不是采取某种效果的方法。 (见参考:http://webpack.github.io/docs/code-splitting.html#es6-modules

  4. 建议的改进和修复:

    // 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,你可以摆脱它。