简体   繁体   English

使用命名空间将代码从ES5迁移到ES2015

[英]Code migration from ES5 to ES2015 with namespace

We have a cross-platform application based on Polymer and Chromium . 我们有一个基于PolymerChromium的跨平台应用程序。

Currently all our JavaScript dependencies are maintained in index.html by importing them in the right order! 当前,我们所有的JavaScript依赖项都以正确的顺序导入index.html进行维护! 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. 为了将来节省,我们决定采用其模块化方法来使用ES2015

Now we need to redesign our JavaScript files to be able to maintain the dependencies between single JavaScript modules. 现在,我们需要重新设计JavaScript文件,以能够维护单个JavaScript模块之间的依赖关系。 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 . 从上面的代码中可以看到,初始化已执行并分配给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 如何在ES2015中使用名称空间
  • How to automatically execute closures 如何自动执行闭包
  • How to export functions of the modules but not in the global scope! 如何导出模块的功能,但不在全局范围内!

Using export { xxx }; 使用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 在此示例中为app_ns.app

"Using export { xxx }; is exporting all functions inside {...} in the global scope, right?" “使用export {xxx};是否在全局范围内导出{...}内的所有函数,对吗?” Is not quite correct. 不太正确。 It exports it to the scope that imports it. 它将导出到导入它的范围。 Right now browsers do not have a way of handling modules natively so most bundlers convert it CommonJs standard and scope it so it doesn't clobber global. 目前,浏览器还没有本地处理模块的方法,因此大多数捆绑程序都将其转换为CommonJs标准并对其进行范围限定,从而不会破坏全局。 I would reevaluate if name spaces are needed under the module paradigm. 我将重新评估模块范式下是否需要名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM