Nodejs - redefining `require` on the client (but not on server) for code-sharing

Redefining nodejs' require on the client, but not on server for code-sharing

I want to share a piece of coffeescript code between the server and the client on Express. I linked the file from the server directory into the /public directory, so it can be loaded by the client. It does have external dependencies, which I resolve statically for the client. To remove the error messages when the client tries to call require, I thought a simple conditional declaration would do.

console.log require
unless require?
  require = (what) ->
    console.info "this is the client, you asked me to load #{what}"
    return {}

However, when run on the server, undefined will be printed and require will be overridden. The same happens for embedded Javascript:

`if( typeof require == "undefined" )
  var require = function(what) {
    console.info( "this is the client, you asked me to load "+what );
    return {};
  }
`

If I only run:

console.log require

on the server, it prints an object structure, as expected. It seems that require is injected after at least the conditional has been evaluated and executed.

How can I override require safely, or what other paradigm might I use for sharing code between client and server?

I recommend using browserify for sharing code between the client and server. It allows you to write your javascript as you would for the server following the common js pattern, but provides a mechanism to build your module for client-side where require() works in the browser.

CoffeeScript is supported with browserify via a transform process. Coffeeify is one implementation of a transform implementation for CoffeeScript.