Isomorphic (aka universal) JavaScript code can be either environment agnostic or shimmed per environment. It means that it cannot contain browser-specific (window) or server-specific (process.env
, req.cookies
) properties. Alternatively, it must provide shims for accessing such properties so the module can expose a single API (window.location.path
vs req.path
).
Many modules in the npm repository already have this trait. For example, the Moment.js
can run in both Node.js and browser environments as the following code demonstrates:
Server (Node.js):
import moment from 'moment'; moment().format('MMMM Do YYYY, h:mm:ss a');
Client (browser):
<script src="moment.js"></script> <script> moment().format('MMMM Do YYYY, h:mm:ss a'); </script>
Module bundlers such as Browserify or Webpack allow to bundle and optimize JavaScript code for a specific environment. Later in this chapter, you will see how we use Webpack to generate two bundles from the same source code, one of which is optimized for running in a browser and another one is optimized for Node.js environment.