Chapter 15: Code Sharing

In the Introduction of the book, I referred to one of the most appealing aspects of Node.JS: the fact that JavaScript, the language it empowers, is the only language supported by browsers.

Even though so far you have been writing code in JavaScript alone, which reduces the mental overhead of having to switch contexts between languages when working on web applications, you haven’t taken advantage of the unique opportunity of writing code once and running it everywhere.

This chapter analyzes what use cases are optimal for code sharing and how to solve common language compatibility problems. You also learn how you can write modular code with the best practices of Node that can be compiled to run in the browser without bloat by using browserbuild.

What can be shared?

The easiest way to answer whether a certain piece of code can be shared between the browser and server is to break down this question into two questions:

• Is it worthwhile to run the codebase in both environments?

• Do the APIs it depends on exist in both environments? If not, can they easily be replaced or added (also known as shimming)?

Answering the first question is normally easy, and the answer itself depends exclusively on your program and project. Answering the second question can be a little trickier.

In Chapter 2, you saw that certain APIs that you commonly associate with JavaScript are not a formal part of the language but a standard API added on top of it by browsers. Examples ...

Get Smashing Node.js: JavaScript Everywhere, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.