I have a node app that uses ES6. I'm using Babel for transpiling.
As far as i understand use a build system like Gulp for example or use the require hook .
The Require Hook approach seems appealing to me since i will be able to keep my source files in ES6 but still execute them using node server.js
without the use of some build system.
This seems extremely useful for develop at least, my main concerns is about the use of this approach in production.
For context i'm using it with an Express app.
Then add a file called .babelrc file to your project. This is the configuration file for Babel, and we will use it to tell babel to transpile ES6. Then you can transpile the file myES6Code.js with Babel like this: This command takes myES6Code.js as input and outputs JavaScript to the console.
This is where Babel comes into play. Babel is a transpiler that can compile ES6 and ECMAScript to old Javascript (ES5) that all browsers can understand. Babel takes some JavaScript code as input, for example code using ES6 Template Strings, and generates some plain JavaScript output.
To use these ES6 syntaxes in node we will use Babel. Now You are thinking what the heck is babel?? Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.
An ES6 module is a JavaScript file containing functions, objects or primitive values you wish to make available to another JavaScript file. You export from one, and import into the other. Any serious modern JavaScript project should consider using modules.
Does it have any penalty hit every time that a user makes a request ?
No, not in the sense that it would have to re-transpile the code on every request.
How this works exactly ?
The require hook basically hi-jacks all subsequent calls to require()
, and performs the ES6->ES5 transpiling prior to that module being executed.
I've been using the babel require hook in production for awhile now (with moderate traffic levels -- peak traffic in the mid-hundreds req/sec range), and it's never been an issue.
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