Setting up Webpack + Babel + ReactJS

I started using Webpack module bundler recently and thought I would document some of my learning. In the past couple of posts I wrote about bundling JavaScript projects using Browserify module bundlers. Webpack can be used as a replacement for Browserify; but it has some nice additional features like bundling of static files and code splitting.

This post is not meant to be tutorial on Webpack, I just wanted to describe how to configure Webpack, specifically using Webpack loaders for Bablel and ReactJS. I will show how to build a JS project using standalone Webpack and also using Webpack APIs in Gulp. The project is available on Github at https://github.com/ramkulkarni1/WebpackBlitzReactStarter

Module Dependencies

Node packages required to build the project are, of course, in package.json. If you are using above starter project from Github, then run ‘npm install’ to install all the required packages. Else make sure you install all the packages listed in devDependencies of package.json . The list contains babel, required babel presets for ES6 and ReactJS, webpack and webpack-dev-server, webpack loaders for babel, LESS and CSS.

Webpack Configuration

Webpack configuration is specified in webpack.config.js. This config file is read when you run webpack or webpack-dev-server command. Optional gulpfile.js (to build the project using Gulp) also loads this file and passes to Webpack APIs.

Here is a brief description of some of the entries in the config file – Continue reading “Setting up Webpack + Babel + ReactJS”

Using ReactJS with Babel and ES6

I wanted to create this post shortly after the last post about Setting up ES6+Babel+Gulp, but it got delayed for some reasons. Anyways ..

Though it is not very complicated to setup ReactJS to work with Babel, there are a few non-obvious things you need to be aware of, specifically the absence of  auto-binding in ReactJS when coded in ES6. Let’s create a small NodeJS project using Gulp –

Install following packages –

npm install gulp gulp-connect vinyl-source-stream browserify babelify babel-preset-es2015 react react-dom babel-preset-react --save-dev

In addition to packages installed in the last post, here we are installing react, react-dom and babel-preset-react packages.

The directory structure is similar to one in the previous post, except that we add views folder for JSX files.

ES6ReactJSBabelTest
  -- build
  -- src
    -- js
       -- views
    -- html
  -- gulpfile.js

Gulp ‘build’ task is modified to add ‘react’ preset to babelify and add jsx extension to browserify (we want browserify to process .jsx files in addition to .js files) Continue reading “Using ReactJS with Babel and ES6”

Setting up ES6+Babel+Gulp

ECMAScript 6 (ES6, specification at http://www.ecma-international.org/ecma-262/6.0/) has many nice features, but presently not all browsers support ES6. However you can still develop your applications in ES6 and make it run in all browsers. For this you need what is called as transpiler – which converts ES6 code to ES5, which all browsers understand currently.

One of the popular transpiler is Babel . In this post we will see how to use Node.js (https://nodejs.org/), Gulp.js (https://gulpjs.com/), Browserify (http://browserify.org/)  to compile ES6 code to ES5.

Gulp is a build tool for Node.js applications. Browserify resovles ‘require’ modules of Node.js and bundles all modules in one file. We will first use browserify to combine all our JS code in one file and then feed the output to babelify to translate the code to ES5. Structure of this sample project is as follows –

ES6BabelTest
  -- build
  -- src
    -- js
    -- html
  -- gulpfile.js

Not all the files are folders are shown above, for example package.json and node_modules folder are not shown.

Continue reading “Setting up ES6+Babel+Gulp”

Using JavaScript Promises with Cordova

JavaScript Promises

JavaScript Promises could make asynchronous programming a bit easier. Most of the APIs of Cordova are asynchronous. So when you want to call one asynchronous API after the other, you have to nest API in the callback functions of the previous API. Many APIs also take error handler as one of the parameter to API function. At some point the whole code could become very difficult to read and maintain.

JS Promises  could make this a bit simpler. Promise is an object, which takes a function callback with two arguments, resolve and reject. Promise represent a value that would be resolved sometime in future, it is is not already resolved or rejected. The promise can be rejected explicitly or when any JavaScript exception is thrown. See https://promisesaplus.com/ and Promises on MDN for details on JS Promises. Advantages of Promises is realized when you need to chain multiple asynchronous calls. Promises can also be useful if you want to guarantee then a piece of code is executed only once. Promises are executed only once. Continue reading “Using JavaScript Promises with Cordova”

Encrypting data with Crypto-JS in JavaScript


I have been working intermittently on a HTML5 mobile application for some time now. This application stores some sensitive date locally (it is a standalone mobile application) and I did not want to store the data in clear text. I wanted to make retrieval of data difficult to some extent, if the device ends up in the wrong hands. So the data had to be encrypted. The application code is in JavaScript, so I started looking for a JS library that can encrypt data. I found that Crypto-JS met my requirements and it was easy to use too.

Before I proceed further, I must confess that my knowledge of encryption and digital security in general is very basic. So the solutions discussed in this post may not be the best in terms of protecting the data.

As I said, Crypto-JS is very simple to use. You can use different cipher algorithms like AES. DES etc. and APIs are simple. e.g. to encrypt using AES , you would call –

encryptedData = CryptoJS.AES.encrypt(textToEncrypt, secretPhrase); //include aes.js script

In the above API, the first argument to encrypt function is text data you want to encrypt, e.g. password. The second argument is a secret phrase (also called passPhrase). This could be any text. Secret phrase is the key that is used to encrypt the data. However you will have to use the same key (secret phrase) when decrypting the data. Continue reading “Encrypting data with Crypto-JS in JavaScript”

ColdFusion Splendor – When to use invokeCFClientFunction

I have seen some confusion when it comes to using invokeCFClientFunction. I have been asked this question a few times, more recently on LinkedIn, so I thought explaining it in a blog post might be a good idea.

If you don’t know already, ColdFusion Splendor has added support for client side CFML (<cfclient>) and this code is translated to JavaScript.  You can call JavaScript functions from cfclient and vice versa.

cfclient also makes calling asynchronous functions of PhoneGap easy by providing synchronous access to them. All device APIs are asynchronous in nature, but in cfclient block you call then as synchronous functions and ColdFusion translates them to asynchronous PhoneGap functions. All function starting with ‘cfclient.’, e.g. cfclient.camera.getPicture(), are asynchronous. In addition to device APIs, data access function, executeQuery and tag, cfquery, are also asynchronous in cfclient.

When you call asynchronous functions in cfclient, ColdFusion takes care of chaining callback functions – any code following an asynchronous function goes in the success callback function. But if you call asynchronous cfclient function form JavaScript code block, then ColdFusion compiler does not touch it. Note that if a UDF in cfclient block calls any asynchronous function (e.g. cfquery or any device APIs) then that function also becomes asynchronous.

Let’s see an example. In the following code, I have a UDF in cfclient block, createDatabase. It does not need any argument, but let’s say it takes one argument, arg1. This function calls queryExecute function, which is an asynchronous function – so createDatabase function also becomes asynchronous. If you call it from JavaScript and have some JS code to be executed only after database is created, then calling createDatabase function directly from JavaScript is not going to work as expected – Continue reading “ColdFusion Splendor – When to use invokeCFClientFunction”

Parsing JavaScript code using Mozilla Rhino

Last year I had blogged “Understanding AST created by Mozilla Rhino parser“, where I exaplained how to traverse AST to get all functions and variables. Since then I have received some comments, public and private, to provide sample code. So here is an example of how to parse JavaScript code and get all functions and variables using Mozilla Rhino.

Note that my intention here is not to build the complete symbol table for any given JavaScript code. And I have not run a lot of test cases on this code. The idea is to show how AST could be traversed and how hierarchy of symbols (functions and variables) be built .

So, for example, if you feed following JavaScript code to this program –

function func1()
{
	var local1 = 10;

	global1 = 20;
}

obj1 = {
	objFunc1 : function()
	{
		var local2 = 30;
	},
	objProp1 : "prop1"
}

You will get following output –

Function : func1
		local1
	global1
	obj1
	obj1
		objFunc1
		Function : objFunc1
			local2
		objProp1

Yes, I know there are duplicates for object and closure – because they are first processed as variable names and then object/closure. This can be easily fixed, but I am going to leave it that way to keep the code simple. Continue reading “Parsing JavaScript code using Mozilla Rhino”

Record and Playback Drawing in HTML5 Canvas – Part II

A reader of my blog post De/Serializing Recordings in Recordable HTML5 Canvas had asked me how to change stroke color and size when recording. I told him that this could be done by adding actions, like setColor and setStrokeSize. For more information about how the recordable canvas was implemented, see my blog post Record and Playback Drawing in HTML5 Canvas . I have updated the example with following new features –

  • Setting stroke color and size – both for drawing and recording
  • Pausing and resuming recording. You may want to pause recording if, for example, you do not want to record time delay when you select stroke color/size. Duration of time that the recording is paused is skipped when playing back the recording.

Here is the demo of how the new features work. Select a color by clicking on any color box on the right side of the canvas. Default selection is black. Currently selected color is displayed in a little bigger box with rounded corner. To select stroke size, I have added a few predefined circles of different sizes on the right side. Currently selected stroke size is displayed in black.

Continue reading “Record and Playback Drawing in HTML5 Canvas – Part II”

Framework for interacting with embedded WebView in iOS application

Last year around the same time I had written a post about Calling Objective-C code from JavaScript in iOS applications . I created a simple framework for it and described how to use it in that post.

Recently I was working on an application that required WebView to be embedded in the same View Controller along with other native iOS controls. I decided to use the above framework, but knew that  my ViewController class will have to extend WebViewController class of the framework. Though I could have done that, I thought separating the functionality of UIWebViewDelegate from the WebViewController would be a better design. So I replaced WebViewController with WebViewDelegate which implements UIWebViewDelegate protocol. I also removed getInitialPageName method from WebViewInterface.h . So here are the files in the new framework – Continue reading “Framework for interacting with embedded WebView in iOS application”

De/Serializing Recordings in Recordable HTML5 Canvas


Last year I blogged about creating a recordable HTML5 Canvas. I explained how to record strokes/drawings created on a HTML5 Canvas and play them back. There are a couple of comments on that post asking me to explain how to save recordings and load them back. Serialization and deserialization of recordings was on my to-do list for a long time and finally this week I got around to implement it. There are different ways to serialize and deserialize recordings, and I have implemented a simple method – using JSON. The serialized data is a bit verbose because of descriptive variable names I have used, but you can change that easily.

RecordableDrawing (in this script file) function remains unchanged. I have added a new file drawingSerializer.js . Two important functions in this file are serializeDrawing and deserializeDrawing.
serializeDrawing takes a RecordableDrawing object as argument and returns JSON string containing array of recordings.
deserializeDrawing takes a String (serialized data) as argument and returns array of Recording objects.

To see how serialization and deserialization works, follow these steps – Continue reading “De/Serializing Recordings in Recordable HTML5 Canvas”

Social