有什么方法可以减少 babel.js 生成的可重用代码吗?

Are there any ways to reduce the reusable code generated by babel.js?

我正在尝试使用 ECMAScript 6 构建我的网站,我选择 babel 作为编译器。

现在如果有两个模块modA.jsmodB.js如下图:

// modA
class A {
    a: 1
}


// modB
class B {
    b: 1
}

编译后会生成两个新文件:

// modA
define(["exports"], function (exports) {
    "use strict";

    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

    var A = function A() {
        _classCallCheck(this, A);
    };
});


// modB
define(["exports"], function (exports) {
    "use strict";

    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

    var B = function B() {
        _classCallCheck(this, B);
    };
});

显然,_classCallCheck 函数可以重用,事实上,如果我使用更复杂的 ES6 功能,如生成器,就会出现更多重复代码。

所以我的问题是:如何减少这些代码,也许是通过将它们移动到 public 模块中?

(ps: 我使用 gulp 作为我的构建系统)

老实说,它被编译为优化以在 JS 验证器(例如 JSHint 或 JSLint)上进行验证。如果你不想要冗长的编译代码,你可以简单地在 Javascript 缩小器上缩小它们,例如 http://jscompress.com/

否则,您可以简单地使用 jQuery 并编写优雅的模块化 Javascript 代码。 https://learn.jquery.com/code-organization/concepts/

How can I reduce these code, maybe by moving them into a public module ?

Babel 已经为您完成了 runtime:

Babel uses very small helpers for common functions such as _extend. By default this will be added to every file that requires it. This duplication is sometimes unnecessary, especially when your application is spread out over multiple files.

This is where the runtime optional transformer comes in. All of the helpers will reference the module babel-runtime to avoid duplication across your compiled output. The runtime will be compiled into your build.

...

The package babel-runtime is required for this transformer. Run npm install babel-runtime --save-dev to add it to your current node/webpack/browserify project. babel-runtime does not support AMD module loaders like RequireJS.

...

Usage

require("babel").transform("code", { optional: ["runtime"] });

$ babel --optional runtime script.js