I was tired of manually creating namespace objects for my javascript files so I decided to dynamically generate a namespace.js file based on the directory structure of my app.
Requirements
Node Modules
Instructions
Download and install a node.js binary.
Create a project folder and navigate to it:
Install the npm modules. The -S flag will save the dependency info to your package.json file:
Set up express in your app. If you don’t know how to do this, check out the express guide or checkout the Using express(1) to generate an app section in the guide to auto generate a node.js / express app.
In your server.js or app.js file (which ever one you’ve created for express) do the following:
Make sure you are requiring the nescessary modules. You probably need more but these are just for the code in this example:
To run the http server in express you probably have something like this in the file:
To auto generate the namespace file when the http server starts, modify the http.createServer code block to look like this. Make sure to replace following variables:
- startPath - path where your app directory resides in relation to the server.js / app.js file.
- appName - global namespace.
- filePath - path of the file you want to write the namespace code to.
With this example and this app directory structure
the autogenerated namespace file looks like this:
This way I can take the following file:
and use the following namespace / naming convention code to define a global method / object:
I got a twitter response from a one of the great JavaScript masters Dr. Axel Rauschmayer when asking if his lobrow library could be used to do this only using browser modules. I wasn’t able to do it and wound up with this solution but he gives some tips:
I hope someone finds this helpful!