- Published on
Understanding Babel
- Authors
- Name
- hwahyeon
As introduced on its homepage, Babel is a JavaScript compiler. However, to be precise, Babel is a transpiler that converts modern JavaScript syntax into code compatible with the specified target environment. Additionally, Babel can transform TypeScript and React JSX syntax into executable code for the target environment. However, Babel does not perform type checking for TypeScript, so if type checking is needed, it is recommended to use the TypeScript compiler (tsc
) alongside Babel.
Babel provides various presets and plugins to transform code. For example:
require('@babel/core').transformSync('const add = (a, b) => a + b;', {
presets: ['@babel/preset-env'],
})
In the above example, even if you write modern JavaScript syntax like an arrow function, Babel converts it into code that can run in the specified environment.
During development, you can use babel-node
to execute modern JavaScript without a build process. For example, you can add the following to the scripts
section of your package.json
:
"scripts": {
"dev": "babel-node index.js"
}
Then, running the command npm run dev
will execute the index.js
file even if it is written with modern syntax. However, since babel-node
performs Babel transformations at runtime, it can cause performance issues. Therefore, it should only be used in the development environment, and pre-built code should be used for production environments.