@babel/preset-env is a smart Babel preset that allows for transpiling modern JavaScript code to code compatible with specified browsers. It automatically detects which JavaScript features are supported by the target browsers and loads only the necessary plugins and polyfills.
Main functions of @babel/preset-env:
- Targeting browsers: Allows specifying target browsers using a configuration file (e.g., browserslist).
- Automatic polyfill loading: With the
useBuiltIns
option, polyfills are loaded only when needed. - Modularity: Loads only the plugins necessary to transpile specific JavaScript features.
Example configuration of @babel/preset-env:
- Installation:
npm install --save-dev @babel/preset-env
- Configuring the .babelrc file:
{ "presets": [ ["@babel/preset-env", { "targets": "> 0.25%, not dead", "useBuiltIns": "entry", "corejs": 3 }] ] }
Benefits of @babel/preset-env:
- Code optimization: Loads only the necessary polyfills and plugins, minimizing the final bundle size.
- Flexibility: Allows precise targeting of browsers, enabling the use of modern features where they are supported.
- Ease of configuration: Simple configuration allows for a quick start.
@babel/preset-env is an essential tool in the modern JavaScript ecosystem, enabling the writing of future-proof code that works in all browsers.