How to import javascript code both on the client and on the server side when using node.js?

I have a couple of Javascript functions I need to use both on the server side and on the client side in a node application.

On the server side, I could create a module and require it. I would need to module.exports my functions. Unfortunately, I could not use that code module on the client side, because there is no such thing as require on the client side.

I don't want to maintain the (nearly) same code in two version of the files. Is there a standard/safe way to import Javascript code in a node module? I mean literally, without using require and module.exports? Or is there another solution to my issue?

Upvotes: 1

Views: 963

Answers (3)

Mark Withers
Mark Withers

Reputation: 1482

I have used browserify in the past. It allows you to use common.js style require syntax on the client side. A word of warning, you will probably have to use a single client side entry point, and therefore re-write a lot of your client side code.

Here's the link - borwserify

Upvotes: 1

dryfish
dryfish

Reputation: 1

I'm sure I've seen Ember implement its own require method but I can't find any documentation for it.

On the way I saw http://www.requirejs.org which creates its own new require method which works which both the browser and nodejs.

Upvotes: 0

SLaks
SLaks

Reputation: 887459

You're looking for browserify, which lets you run Node-tyle modules with require() and module.exports in the browser.

Upvotes: 1

Related Questions