Transpile and polyfill JavaScript

We are going to transpile and polyfill JavaScript in this tutorial, we are going to show you two different ways to do this. We are going to transpile JavaScript by compiling as TypeScript and use external polyfills. We are also going to use webpack, babel, core-js and gulp for transpilation and polyfilling.

It is most convenient and effective to use the latest ECMA-standard (es) when we write JavaScript. Browsers have built-in support for JavaScript but they may not support the latest version available. We might need to transpile and polyfill our JavaScript to be able to support older browsers and Internet Explorer for example.

Transpilation is a process used to transform or convert JavaScript to an older standard. Transpiled code may also need to be polyfilled, it might include methods and properties not supported by older browsers. A polyfill is a plugin (code) that includes methods and properties that not is available in target browsers.

You need to have Node.js installed on your system to be able implement this code, install the latest version to get most functionality (I have used v6.11.0).

TypeScript transpiler

TypeScript is a superset of JavaScript and we do not need to change any code to be able to use this method. We are going to compile our JavaScript as TypeScript by using JavaScript Transpiler by Mads Kristensen.

Add a tsconfig.json file in your project, it can be in the root or in the wwwroot folder. Include all files that should be transpiled in a bundle to avoid duplicate helper methods. The configuration file below will transpile two files to a bundle.

{
  "compileOnSave": true,
  "include": [
    "js/annytab.html5.validation.js",
    "js/annytab.effects.js"
  ],
  "compilerOptions": {
    "allowJs": true,
    "sourceMap": false,
    "target": "es5",
    "outFile": "tjs-typescript/bundle.js"
  }
}

We may also need to add polyfills that you can get from polyfill.io. We need to add polyfills for XMLHttpRequest, Array.prototype.includes and Promise in the example above.

<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=Array.prototype.includes%2CPromise%2CXMLHttpRequest"></script>
<script src="js/out/bundle.js"></script>

Webpack transpiler

An alternative to using TypeScript is to use webpack, babel, core-js and gulp as a transpiler. This method allows us to output multiple files if we want and we do not need to find the polyfills that we need. Polyfills is added by babel and gulp is used to run a task before build (Task Runner Explorer).

We first need to add a package.json file to the root directory of our project. This file includes all the npm packages that we need and the contents of the file is shown below. These packages will be installed by Visual Studio.

{
  "name": "annytab-scripts",
  "version": "1.0.0",
  "dependencies": {
    "@babel/runtime": "^7.5.2",
    "core-js": "^3.1.4"
  },
  "devDependencies": {
    "gulp": "^4.0.2",
    "gulp-util": "^3.0.8",
    "@babel/core": "^7.5.0",
    "@babel/preset-env": "^7.5.2",
    "@babel/plugin-transform-runtime": "^7.5.0",
    "babel-loader": "^8.0.6",
    "webpack": "^4.35.2",
    "webpack-stream": "^5.2.1"
  }
}

Next we need to add a .babelrc file (JSON) to the root directory of our project. This file includes settings for babel. We want to support browsers with a market share higher than 0.25 % and we will use version 3 of core-js.

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": "3",
        "targets": "> 0.25%, not dead"
      }
    ]
  ]
}

Next we need to add a webpack.config.js file to the root directory of our project. This file includes settings for webpack. We add files that should be included in entry and the name of files in output. We also tell webpack to use babel-loader and to look for settings in .babelrc.

'use_strict';

module.exports = {
    mode: 'production', // 'production' | 'development' | 'none'
    entry: {
        'polyfill': [
            'regenerator-runtime/runtime',
            'core-js/stable'
        ],
        'annytab.html5.validation' : './wwwroot/js/annytab.html5.validation.js',
        'annytab.notifier' : './wwwroot/js/annytab.notifier.js'
    },
    output: {
        filename: '[name].min.js'
    },
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    }
};

We will run transpilation and polyfilling with a gulp task, this makes it possible to always transpile and polyfill before we build our project. Add gulpfile.js to the root of your project, if i doesn’t exist already. Add the following contents to the gulpfile.js file.

var gulp = require('gulp');
var gutil = require('gulp-util');
var webpack_stream = require('webpack-stream');

// Create a task
gulp.task('transpile', function ()
{
    // Log that work is starting
    gutil.log("Processing files!");

    // Process webpack configuration
    return webpack_stream(require('./webpack.config.js'))
        .pipe(gulp.dest('./wwwroot/tjs-babel/'));

});

Task Runner Explorer in Visual Studio will help you find gulp tasks. You can use Task Runner Explorer to run a task, debug a task and to add bindings for when a task should run (before build for example).

Leave a Reply

Your email address will not be published. Required fields are marked *