Write javascript code that works with client side javascript and server side NodeJs modules
express, javascript, node.js
Solution
To make it work both client-side and server-side, just export it if `module.exports` exists:
var MyModule = function () {
this.attribute = 666;
};
if (typeof module !== "undefined" && module.exports) {
module.exports = MyModule;
}
This, and similar ways are used by a lot of libraries to enable packages to be used on CommonJS and the browser (e.g.: jQuery)
Problem
Browserify and lo-dash, do something special. Ok, but should like to be free from other vendor libraries or nodejs modules. I want to write reusable code. So, ... I can write some javascript code. Also, I can write NodeJs code. Ok: I can write a module for NodeJs, for server-side code but at some point I need to write a NodeJs code to export, for example, a module. ``` var MyModule = function () { this.attribute = 666 } module.exports = MyModule ``` But, ... it's a NodeJs module. If I try to include it in client page ... ``` <script src="lib/myModule.js"> ``` I'll get 'Uncaught ReferenceError: module is not defined'. Why? Maybe, because it's NodeJs code, and not Javascript. Ok but, ... Which are best practice to share same code in client and server side with NodeJs. Ok, I can share a javascript file, and use it in both sides. How can I write a module, that works with a javascript code, that I want to use also in client side? What I am looking for, is: Write some javascript code. my_public_file.js: ``` console.log('I am a javascript snippet') ``` Then, I want to write a module that works with same code. my_module.js ``` var lib_public_code = require('some/public/path/my_public_file.js') var MyModule = function () { this.attribute = 666 } module.exports = MyModule ``` And, also, I wanto to write a public web page (index.html) that works with the same code ``` <script src="javascript/my_public_file.js"> ``` Best practices? I am insane?