Transpile ES7 To ES6 For Modern Browsers

I have a react application written in es6/7 which I am happily transpiling using babel to es5 to be compatible with all browsers.

This got me wondering...

Is it possible to create a js bundle transpiled to es6 which then could be served by say nginx if it is a modern browser? This should save on file size and possibly execution time.



Yes, you can use Babels env preset to create multiple versions of your bundles that provide various levels of browser compatibility.

For example, this .babelrc will create a bundle that is compatible with Firefox version 50 and upward:

  "presets": [
    ["env", {
      "targets": {
        "browsers": ["Firefox > 50"]

Without any parameters, the env plugin will create a bundle that works on a wide range of browsers, which probably will be much bigger than one built specifically for a modern browser like Firefox:

  "presets": ["env"]

The env preset uses browserslist to specify the browsers that Babel should use as transpilation target. Browserslist features a query language that lets you specify browsers by type, platform, version, usage statistics, etc. Check out their documentation to figure out which queries to use for your specific audience.

You can try out the browserslist queries on the command line like this:

npx browserslist "> 10%, last 3 versions"

This gives you a list of the last 3 versions of browsers whose usage is higher than 10%.

Once you've figured out which browserslist queries work for you to create a big bundle for maximum browser compatibility and a slimmer one for modern browsers, you can use the ngx_http_browser_module to serve the bundle depending on the user agent of the incoming request.