This may sound a little perverse, but I would like to adapt part of a pretty large JavaScript codebase so that it can be run on NodeJS. The code is written in the CommonJS style, with a gulp
build process that uses browserify
and deamdify
. I didn't set any of this stuff up, and I'm only passingly familiar with the AMD vs CommonJS patterns.
I want to do this in order to convert some of the code to a server-side API, for performance - but it still needs to be able to run in the browser.
At first I thought I could simply use the libraries without running browserify, but I run into errors like this:
ReferenceError: define is not defined
because some of the libraries are written like this:
/*global define*/
define([
'./defaultValue'
], function(
defaultValue) {
"use strict";
So it looks like I need to run deamdify
, which is a browserify transform...hence I need to run browserify?
However, one downside of that seems to be that it generates a monolithic Javascript
file (of course), which is then all parsed, and fails because it contains references to browser objects (document.location
) which don't exist. I was hoping to just not use the bits of code that refer to browser objects.
So my questions:
- Is there any guidance on how to proceed? Any tutorials? I couldn't find much on Google, but I may well be using the wrong terms.
- Is there a NodeJS equivalent to Browserify? It seems a bit weird and unnecessary to build a monolithic Javascript file and then run that server-side.
Using a (large) browser code base inside node can be challenging. I guess creating an environment module that provides a fake browser environment for node could do the job, this could be a lot of work though, you would have to change every browser environment reference to window
etc. with a reference to the environment module. There you could decide in which environment the code is running and provide the appropriate behavior (e.g returning the window
object in browsers and something different in a node environment).
First off: browserify is a library that runs on top of nodejs, so the "NodeJS equivalent to Browserify" makes no sense... as for avoiding the single javascript file: there are node modules that enable you to use AMD modules in node (e.g. amdrequire, node-amd-loader), maybe that could help. Another way is to convert the AMD modules to node modules - it depends on the amount of AMD modules.