Babel is a powerful JavaScript compiler that
- Transforms modern JavaScript (ES6+) into backwards compatible code
- Enables JSX transformation for React
- Allows custom code transformations through plugins
- Provides polyfills for new JavaScript features
An Abstract Syntax Tree (AST) represents the syntactic structure of source code in a tree format. Each node in the tree represents a construct in the source code.
- Parse: Convert source code into AST
- Transform: Modify AST using plugins/presets
- Generate: Convert modified AST back to code
# Install core dependencies
npm install --save-dev @babel/core @babel/cli babel-loader
npm install --save-dev @babel/preset-env
module.exports = function (babel) {
const { types: t } = babel;
return {
name: "my-custom-plugin",
visitor: {
// Your transformations here
}
};
};
This plugin adds function names to console calls.
Input:
function test() {
console.log("Hello");
}
Output:
function test() {
console.log("called inside 'test'", "Hello");
}
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['./custom-scripts/babel']
}
}
}
]
}
};
Visit AST Explorer to:
- Visualize AST structure
- Test transformations
- Debug plugin logic
@babel/core
: Main transformation engine@babel/types
: AST node utilities@babel/traverse
: AST traversal@babel/generator
: Code generation
# Start development server
npm start
# Build for production
npm run build