Create React App Custom Templates “cannot find module `cra-template-[template-name]`”

After creating a Create React App custom template and trying to create a project from it locally (npx create-react-app cratest --template file:./cra-template-[template-name]), Create React App failed with a cannot find module error:

cannot find module cra-template-[template-name]

Rather than copy/pasting the package.json from the docs, I’d created my package.json with npm init which by default sets the value of the main property to index.js.

Changing main to template.json, as it is in the Create React App docs was the fix.

More for self reference than anything else.

What’s my altitude?

I’ve been wanting to put something like this together for myself for a while and I finally found myself with a couple of hours to spare today. The main reason is that I have to calibrate my GPS watch with my current altitude to be able to get accurate elevation readings using the watch’s barometer. So to be able to quickly get my current elevation based on map data for my location I thought this would be quite handy (at least whenever I’ve mobile reception).

It’s a little overkill but it’s built in React. There are even a couple of token tests in there – mainly for the sake of using Jest snapshots which I’ve not used up until this point.

It’s a simple little app that takes your location from navigator.geolocation.getcurrentposition, fires it off to the google elevation service (for now at least) which returns your elevation in metres.

It was a bit of a ball-ache setting up the Google API, there’s a lot of configuration to be done in their control panel to make sure you can get requests through and initially I just tried hitting their elevation API directly not realising this was blocked by CORS so I had to use their Google maps Javascript API.

I’m going to look for an alternative API to google’s for getting the elevation as they are charging £0.005 per request. It’s fine for now – when I signed up to their cloud platform I was given ~£220 ($300) free credit. I should be good for about 44000 requests which I’d be surprised to ever come close to.

I had a quick look and came across open elevation but their open API was very slow to the point of unusable. I may look at firing up a Digital Ocean droplet to host my own instance but that’s for a later date (if at all). If anyone has any other suggestions, please do let me know.

It’s all hosted on an S3 bucket. I’m still trying to get my head around AWS so it was a nice little project to have a play with that too.

You can take a look at WHAT’S MY ALTITUDE? and see the code on my Github (if you want to try this out make sure you set up your .env file as per the .README).

Space Beer Cave is now available on iOS devices

Space Beer Cave

A few months back, I released my mobile game “Space Beer Cave” into the Google Play Store. I had full intention of following this immediately with an iOS release, but running a 128Gb Macbook Air with no space left on the SSD prevented me from installing the behemoth that is Xcode.

It took about 6 months, but I finally pulled my finger out and cleared some space from my drive and it is now in the App Store. It’s completely free with no ads or catches. You can download it here.

The game was built in a day using the Phaser.js framework and all packaged up with cocoon.js. I use Phaser quite heavily in my day job and absolutely love it for how easy it is to quickly put together something cool.

Now Space Beer Cave is in the bag, I’m currently working on another mobile game, tentatively titled “Space Bookah”. It uses spot gravity and orbital mechanics (to try and sound fancy). The tricky game mechanics are in place and I now just need to flesh it out and create all the levels and story. This is going to be a more complex game than Space Beer Cave so will be a much lengthier process to get the game out around my full time job, social life and training.

Error on “npm install gulp –save-dev”

Using a PC at work so unable to reap the benefits that I get from CodeKit 2 on my mac at home, I’ve mean meaning to get Grunt or Gulp into my workflow.

Always one to jump on a bandwagon, I decided to choose Gulp over Grunt as the newer task runner seems to be gaining traction over the warthog. A sucker for a logo, I also prefer the Gulp logo.

Starting a new project this afternoon, I decided to spend the final hours of the working week getting set up and accustomed to Gulp.

Our dev server at the office is running Ubuntu 11.10 so it was a bit of a struggle updating dependencies to actually get node.js installed. A bit of brainstorming with Sam (read: Sam, the unix genius, took the reins did it for me) and node was installed.

Following the setup instructions I hit a hurdle when trying to install Gulp to my project folder. With the command:

npm install gulp --save-dev

I was getting a lengthy error:

npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm ERR! Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json']
npm ERR!   stack: 'Error: EACCES, chown \'/path/to/dir/htdocs/node_modules/gulp/package.json\'\n    at Error (native)',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_finish_call: 'chown',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7',
npm ERR!      'Object.oncomplete (evalmachine.:93:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.0.0-12-generic-pae
npm ERR! command "node" "/usr/local/bin/npm" "install" "gulp" "--save-dev"
npm ERR! cwd /path/to/dir/htdocs
npm ERR! node -v v0.13.0-pre
npm ERR! npm -v 1.4.26
npm ERR! path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call chown
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! stack Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR! stack     at Error (native)
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7
npm ERR! fstream_stack Object.oncomplete (evalmachine.:93:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /path/to/dir/htdocs/npm-debug.log
npm ERR! not ok code 0

After A LOT of trouble shooting, we discovered the issue was caused by npm being unable to change of the owner of package.json because the drive the site resided on (a mounted NAS) was in NTFS format. Rather than pull my hair out and try and find a work around, I moved the site to the main drive and everything was gravy.

CodeKit 2 replacing hostname instances with preview URL

After settings up a new project for a quick static build using CodeKit 2, I noticed some strange (and buggy) behaviour an interesting feature.

It appears that when previewing a project through CodeKit 2’s preview, it replaces all instances of the hostname specified in the project’s “External Server Address” with the preview URL.

In my case, I’d set up my host in MAMP Pro as “GWAC”, pointing to this in CodeKit 2’s
“External Server Address”

mampScreen Shot 2014-09-09 at 8.49pm


Wherever the string “GWAC” appears in my files, it is replaced with CodeKit’s preview URL. ie:

Screen Shot 2014-09-09 at 8.53pm


Screen Shot 2014-09-09 at 8.54pm


This is expected behaviour. Makes sense:


PHP Recursive Function to Build a Site Tree / Site Map

A problem faced fairly regularly is the need to generate a site tree either for a menu or a site map.

Assuming your page structure in your database is along the lines of:

intPageId strPageName intParentId
1 Top Level Page X 0
2 Top Level Page Y 0
3 Child Page X 1
4 Grandchild Page X 3
5 Grandchild Page Y 3

Giving you a visual structure of:

Site tree structure

I’m a developer, not a designer. Don’t judge me

You can achieve this fairly simply in with the following PHP recursive function to get your page structure into an array. Note, I have used the Laravel query builder in this example as the project I wrote this for was a Laravel project, but this can be swapped out with a query builder from whatever framework you are using or with PHP’s PDO (or any of the lesser PHP APIs for working with databases).

function generateSiteTree($startAt)
	if ($children = \DB::table('cms_pages')->where('intParentId', '=', $startAt)->get())
		$thisLevel = array();
		foreach ($children as $child) 
			$thisLevel[$child->intPageId] = $child;
			$thisLevel[$child->intPageId]->children = generateSiteTree($child->intPageId);
		return $thisLevel;
$tree = generateSectionSiteTree(0);

That’s it.

Bonus recursive function

The project I wrote this function for required me to be able to reel off the site tree only for the top level parent of the current page, regardless of however deep you currently are.

This is easily achieved with this function:

function recurseToFindSectionParent($pageId)
	$current = \DB::table('cms_pages')->where('intPageId', '=', $pageId)->first();
	if ($current->intParentId == 0) //we've reached the top of the chain
		return $current->intPageId;
	else //keep going
		return recurseToFindSectionParent($current->intParentId);
$topParentID = recurseToFindSectionParent($currentPageId);

You can now feed the ID of the top level parent into the generateSiteTree function:

$tree = generateSiteTree($topParentID);

Upload Progress Bar with jQuery

Another quick post detailing a method for creating an upload progress bar with jQuery for file uploads. More for self reference than anything.

This example is using XHR.upload.onprogress to return a loaded (bytes uploaded) and total (total bytes of the file) value so an upload progress can be computed. We are using the jQuery form plugin for uploading files. We take the “loaded” and “total” values to display and update a progress indicator (status bar and the displayed percentage). Once the AJAX upload has completed, we reset and hide the progress indicator.


    target: '#output',
	xhr: function()
		myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload)
            myXhr.upload.addEventListener('progress', function(ev){
            	if (ev.lengthComputable) {
	                var percentComplete = Math.round((ev.loaded / * 100);
			$('#percentage').text(percentComplete + '%');
			$('#status').css('width', percentComplete+'%');
            }, false);
            myXhr.upload.addEventListener('load', function(ev){
		$('#status').css('width', '0%');
            }, false);
        return myXhr;
	dataType: 'json',
        success:  afterSuccess

HTML for the progress indicator:

<div id="progressBar">
	<div id="status"></div>
	<div id="percentage">0%</div>

CSS for the progress indicator:

	width: 350px;
	text-align: center;
	height: 16px;
	position: fixed;
	left: 50%;
	margin-left: -175px;
	z-index: 9;
	border:1px solid #9d9d9d;
	border-radius: 5px;
	overflow: hidden;
	top: 45px;
	display: none;
#progressBar #status{
	width: 0%;
	height: 16px;
	transition:1s linear width; /*this gives a smooth effect as the progress increases*/
#progressBar #percentage{
	position: absolute;
	text-align: left;
	z-index: 11;
	top: 0;
	font-size: 12px;
	color: #ffffff;
	width: 350px;
	padding-left: 5px;
	line-height: 15px;

Upload progress bar with jQuery

Upload progress bar with jQuery

Note: When developing this, I had an issue with the progress being reported waaaaay too fast. On file uploads of ~70Mb the progress would shoot to 100% in a couple of seconds and the upload would churn away in the background until it was complete. I made a post on Stack Overflow and someone suggested that it could be due to antivirus on my machine. I tried on a machine without AV and sure enough it worked great. I’ve tried turning off AV on my work dev machine and it behaved as expected (I’m unsure if it’s anything to do with the brand of anti virus but I have avast on my work machine).

IE8 prompting to download jQuery JSON response

I had a few JSON calls which IE8 was prompting me to download/save the response rather than simply hand it to jQuery to do it’s thing.

The returned JSON had the “correct” header and no other browsers were experiencing any issue:

header('Content-type: application/json');

To get around the IE8 issue, I had to change the header of the returned JSON to return text/plain:

header('Content-type: text/plain');

and ensure that my JSON calls had the dataType “json” specified. Without this explicitly specified, the browser was unable to parse the returned JSON.

	type: "POST",
	dataType: "json",
	url: URL,
	success: function(data){


As an extra note, I was also using dropzone.js for drag and drop file uploads. Dropzone.js doesn’t allow you to force the datatype of the response so I had to convert the response to JSON before doing anything with it with:


(Note, JSON.parse is only supported in modern browsers, this was not an issue though for me though as only modern browsers were able to use the dropzone functionality anyway and I had a fallback in place for older browsers)

PHP sessions not setting in Internet Explorer (IE)

I just made a pretty interesting discovery in that PHP sessions do not set in IE when there is one or more underscores (_) in the URL.

IE was the last browser I checked an almost completed project in, having developed in Chrome and Firefox. My heart sank when I found I was unable to log in. I hadn’t experienced this issue on any other browser and didn’t have a clue where to even start.

I was able to log in on the staging environment (where I show progress to the client) but not on my local dev so it had to be an environment issue. The only difference between the environments was the URL. I had a play around and found that removing the underscores from my local dev environment URL fixed this issue and I was able to log in. Boom.

jQuery $ is undefined in IE iFrame

I have a very jQuery heavy app which I am including in an iFrame on a site I am working on. Developing in Firefox and Chrome, it was only at the last minute when I came to test the site in Internet Explorer. Much to my dismay I was getting “$ is undefined”. There were no issues when running the site directly in IE (not through the iFrame).

I tried numerous fixes recommended by Stack Overflow including delaying the loading of the iFrame until the main content had loaded, but in the end, it was simply fixed by hosting jQuery from my own server rather than pulling it in from the CDN.