How to integrate legacy JavaScript with NodeJS in the browser

1.1k views Asked by At

Hypothetical legacy scenario:

Say I have 4 scripts that simply get concatenated together as a single script for deployment to provide a utility library with a global namespace in the browser. I then have 1 separate application script that utilizes the library. Something like:

<script src="library.js"></script>
<script src="app.js"></script>

In my app.js script, calls are made to the library methods through its namespace, like

var id = lib.id(prefix);

I see that 1 of the 4 library scripts is a useful utility that I want to turn into a Node module. I copy it and create a package and publish it to npm to use in new development.

Problem: Now I have two versions of this script to maintain - one for Node and one for the legacy library.

Is there a way to have one common file that I can include in both the Node module and the legacy library? Or am I stuck maintaining two versions of the file until we phase out the legacy code?

Additional info:

I looked at browserify and webpack, thinking they might be useful, but both suffer from a problem I don't know how to get around. Unless the end module defines global variables, I can't use the module in legacy code, as there is no require command available. In other words, I can't browserify a Node module, then drop it into a legacy web page and use it in my existing app.js, because I can't call var mymodule = require('mymodule'). Is there any way to get browserify or webpack to define and expose a require function to let me access my new Node module from a legacy codebase? Surely, this is not a unique scenario.

1

There are 1 answers

5
Andrew Eisenberg On

Your best bet is to use a UMD pattern to ensure that the module can be used both as a global and in commonJS (ie- node) systems.

The pattern that would fit best for you is returnExports. This ensures that all exported properties are either applied to the global object (ie- window) or to the module object in node.

Since you are not using AMD, you can simplify the pattern somewhat and remove the first chunk of the if statements on lines 18 and 42.

This will require you to reorganize your code so that it fits in with the pattern.

There are other patterns that you may use, such as commonJsStrictGlobal, but I personally prefer returnExports.