Transpiling ES6 to ES5 for Legacy Browser (IE11) Support with Babel

Svelte outputs modern JavaScript, therefore for legacy browser support, you need to transpile this output back to ES5 (or older). The main strategy people adopt is having 2 builds:

  • Modern JS build - transpile Svelte as is
  • Legacy browser build - add Babel plugin to bundler, after Svelte plugin.

You can use an environment variable like process.env.IS_LEGACY_BUILD (the name is arbitrary - Sapper calls it SAPPER_LEGACY_BUILD) to toggle this behavior between builds.

If you are using Parcel, this should be taken care of by specifying the correct .babelrc.

If you are using Sapper, this should be correctly set up for you.

If you are using Rollup or Webpack, you need to add the respective Babel plugins.

Rollup

Assuming you want to toggle on and off a modern and a legacy build using a IS_LEGACY_BUILD environment variable:

// // rollup.config.js
// other imports
import svelte from 'rollup-plugin-svelte';
import babel from 'rollup-plugin-babel';

const legacy = !!process.env.IS_LEGACY_BUILD;

export default {
	// etc...
	plugins: [
		svelte({
			// etc..
		}),
		// this should come after the Svelte plugin
		legacy &&
			babel({
				extensions: ['.js', '.mjs', '.html', '.svelte'],
				runtimeHelpers: true,
				exclude: ['node_modules/@babel/**'],
				presets: [
					[
						'@babel/preset-env',
						{
							targets: '> 0.25%, not dead'
						}
					]
				],
				plugins: [
					'@babel/plugin-syntax-dynamic-import',
					[
						'@babel/plugin-transform-runtime',
						{
							useESModules: true
						}
					]
				]
			})
		// ...
	]
};

Of course, make sure to have the relevant dependencies like rollup-plugin-babel @babel/core and whatever presets and plugins you use installed.

Webpack

To be written - please contribute!

Published: