2

We have a cross-platform application based on Polymer and Chromium.

Currently all our JavaScript dependencies are maintained in index.html by importing them in the right order! This approach will be a nightmare soon and writing test and to see the test coverage isn't a easy task.

To be future save we decided to jump on ES2015 with it's modularity approach.

Now we need to redesign our JavaScript files to be able to maintain the dependencies between single JavaScript modules. So far so good. But how do we do that to preserve our namespaces, closures etc.?

This is a sample code:

//namespace check
var app_ns = app_ns || { };

// ****************************************************************************
// Module: app
// ****************************************************************************

app_ns.app = (function initialize () {

  // ***
  // basic APIs and definitions
  // ***

  // Application version will be replaced by Gruntfile task.
  // Don't change the version manually!!!
  var AW_VERSION = "1.4.32";

  function version () { return AW_VERSION; }
  ...

  // ***
  // exports
  // ***
  return {
    version : version
  };  
}());

As you can see from the code above the initialization is executed and assigned to app_ns.app. Due to simplicity, the code snippet doesn't show dependencies to other modules but we have those for sure!

So the questions are

  • How to use namespaces in ES2015
  • How to automatically execute closures
  • How to export functions of the modules but not in the global scope!

Using export { xxx }; is exporting all functions inside {...} in the global scope, right? How to bind the exported functions to the correct namespace? In this example to app_ns.app

4

1 回答 1

0

“使用 export { xxx }; 是在全局范围内导出 {...} 内的所有函数,对吗?” 不太正确。它将它导出到导入它的范围。现在浏览器没有本地处理模块的方法,所以大多数打包器将其转换为 CommonJs 标准并对其范围进行调整,因此它不会破坏全局。我会重新评估在模块范式下是否需要名称空间。

于 2016-09-20T14:58:25.383 回答