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)
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
runtimeoptional transformer comes in. All of the helpers will reference the modulebabel-runtimeto avoid duplication across your compiled output. The runtime will be compiled into your build....
The package
babel-runtimeis required for this transformer. Runnpm install babel-runtime --save-devto 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With