How to Distinguish Between Private and Public Classes in Webpack

时间:2017-04-20 17:10:35

标签: javascript webpack ecmascript-6

I'm using web pack to package a library. We have multiple ES6 classes, in this fashion:

/src/Lib.js

import HelperClass from './HelperClass.js';
class Lib {
  method1() {...}
}

/src/HelperClass.js

class HelperClass {
  doSth() {...}
}

Packaging with webpack works, we end up with one file lib.js that contains Lib and HelperClass as var Lib = ....

How can I hide the HelperClass from the global namespace (e.g. make it a private class) with webpack?

UPDATE:

Now I'm running into an issue with importing the HelperClass! I uploaded a sample project https://github.com/benmarten/webpack_es6_test

中获得价值

这一行:

__WEBPACK_IMPORTED_MODULE_0__Helper_js___default.a.doSth();

结果:

[Error] TypeError: __WEBPACK_IMPORTED_MODULE_0__Helper_js___default.a.doSth is not a function. (In '__WEBPACK_IMPORTED_MODULE_0__Helper_js___default.a.doSth()', '__WEBPACK_IMPORTED_MODULE_0__Helper_js___default.a.doSth' is undefined)
method1 (lib.js:92)
Global Code (index.htm:6)

1 个答案:

答案 0 :(得分:1)

使用webpack创建库时,会公开在入口点导出的所有内容,其他所有内容都无法从外部访问,但您可以在代码中使用它。如果要使用其他文件中的任何内容,仍需要将其导出,因为这些文件仍然是模块。仅仅因为有出口,并不意味着它成为一个全球性的。只会公开webpack.config.js中指定的条目中的导出。

HelperClass.js中导出帮助器:

class Helper {
  static doSth() {
    console.log('helper:doSth');
  }
}

export default Helper;

然后将其导入Lib.js

import Helper from './HelperClass.js';

class Lib {
  static method1() {
    Helper.doSth();
  }
}

export default Lib;

现在,您的捆绑包的默认导出将是Lib类,您可以在其中使用Helper而不会暴露它。

您还应该阅读Authoring Libraries Guides