Skip to content
jshacks.dev
Tooling

Configure Babel for a legacy browser target

Configure Babel with preset-env and a browserslist target to compile modern syntax for older browsers, and add polyfills only where code uses them.

1 min read
Summarize in AI

Babel rewrites new syntax into older syntax for the browsers you list. It is the tool to reach for when you still support a browser that lacks a feature.

babel.config.jsJavaScript
export default {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: { chrome: '80', safari: '13' },
        useBuiltIns: 'usage',
        corejs: '3.40',
      },
    ],
  ],
};
src/in.jsJavaScript
const a = user?.profile?.name ?? 'anonymous';
dist/out.jsJavaScript
var _user, _user$profile;
var a = (_user = user) === null || _user === void 0 || (_user$profile = _user.profile) === null || _user$profile === void 0 ? void 0 : _user$profile.name ?? 'anonymous';

preset-env compiles only what the targets need: with a newer target list the same input passes through unchanged. useBuiltIns: 'usage' adds core-js imports for methods the code actually calls, such as Array.prototype.at, not the whole library. Syntax is rewritten; missing APIs need those polyfills. See the preset-env docs.

The exact compiled shape varies by Babel version. Compare the output to your target list now and then: a stale list can make you ship extra code to browsers that no longer matter.

Also inBrowser
Taggedbabel
Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.