How to transpile modern JS to ES5 in Vite?

Learn how to write modern code and don't bother yourself about old browser support.

tl;drGitHub

What browsers Vite supports by default?

The production bundle assumes support for modern JavaScript. By default, Vite targets browsers which support the native ES Modules, native ESM dynamic import, and import.meta, that's why we need to load scripts with type="module" attribute.

Chrome >=87
Firefox >=78
Safari >=14
Edge >=88

We can specify custom targets via build.target config, but keep in mind that Vite only handles syntax transforms and does not cover polyfills. If you want to support older browsers than they, you can follow the steps described in Vite documentation for transpiling the code 😈


What is transpilation and why do we need this?

Let's say that you want to use modern JS features like default params, template literals, arrow functions, let/const, spread, etc. Your cut-off for browser support will be ~2017 (source). So for example, the code below won't work on IE 11.

import Cookies from 'js-cookie';

class Test {
    log() {
        console.log('scripts');
    }
}

const test = new Test();

test.log();
console.log(Cookies.get('wp-settings-time-1'));

Transpiling is like translating code from one version of JavaScript to another. It helps convert code written in newer versions of JavaScript (ES6 or ESNext) into older versions (ES5) that can be understood by older browsers or environments that might not support the latest JavaScript features. This way, developers can write modern code while ensuring it works across different platforms and browsers.

import { a as api, _ as _createClass, b as _classCallCheck } from "./js.cookie-f648e69e.js";
var Test = /* @__PURE__ */ function() {
  function Test2() {
    _classCallCheck(this, Test2);
  }
  _createClass(Test2, [{
    key: "log",
    value: function log() {
      console.log("scripts");
    }
  }]);
  return Test2;
}();
var test = new Test();
test.log();
console.log(api.get("wp-settings-time-1"));

How to transpile code to ES5 in Vite?

In Vite, transpiling code to ES5 is typically handled through the use of plugins.

yarn add @babel/core @babel/preset-env @rollup/plugin-babel --dev

Then we need to configure babel plugin vite.config.js in a following way.

import { defineConfig } from 'vite';
import { babel } from '@rollup/plugin-babel';

export default defineConfig({
  build: {
    rollupOptions: {
      input: [
        'resources/scripts/scripts.js',
      ],
      plugins: [
        babel({
          babelHelpers: 'bundled',
          presets: [
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: ['ie >= 11'],
                },
              },
            ],
          ],
        }),
      ],
    },
  },
});

Feedback

How satisfied you are after reading this article?