Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to build my website with ECMAScript 6, and I choose babel to be the compiler.

Now if there are two modules modA.js and modB.js as shown below:

// modA
class A {
    a: 1
}


// modB
class B {
    b: 1
}

After compiled, two new files will be generated:

// 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);
    };
});

Obviously, _classCallCheck function can be reuse, and in fact if I use more complex ES6 features like generators, more duplicated code will shown up.

So my question is: How can I reduce these code, maybe by moving them into a public module ?

(ps: I've used gulp as my build system)

like image 356
hsfzxjy Avatar asked Jan 25 '26 13:01

hsfzxjy


1 Answers

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

Babel already did this for you with its 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
like image 128
Felix Kling Avatar answered Jan 27 '26 03:01

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!