The oktopost-namespace library aims to implement the usage of Namespaces inside JavaScript projects.
npm install oktopost-namespace --saveThe following example will assume the next directory structure:
src
Example
Subdir
sub.js
sum.js
calc.js
namespace.json
index.js
./src/Example/Subdir/sub.js
Define a new function named
subinside the namespaceExample.Subdir
namespace('Example.Subdir', function ()
{
this.sub = function sub(a, b)
{
return a - b;
}
});./src/Example/Subdir/sum.js
Define a new function named
suminside the namespaceExample.Subdir
namespace('Example.Subdir', function ()
{
this.sum = function sum(a, b)
{
return a + b;
}
});./src/Example/calc.js
Define a new function named
calcinside the namespaceExample
namespace('Example', function ()
{
this.sum = function sum(a, b)
{
return a + b;
}
});./namespace.json
namespace.jsonis the configuration file for the Namespace library.
{
"map":
{
"dir":
{
"Example": "./src/"
}
}
}./index.js
Load and setup the Namespace library. After calling the method
virtual, the functionnamespaceis registered into the global scope and can be called usingglobal.namesapce(...)or justnamespace(...).
var root = require('oktopost-namespace').virtual(__dirname);
module.exports = root.Example;Most initialization methods, including virtual, will return the root object in which all the namespaces are stored.
Few notes:
- Directory names should match the namespace path.
- In the current version,
thisshould not introduce more then one new definition per file into the namespaces scope. Or in other words, don't usethis.something = something;more then once in the same JavaScript file.
Inside your gulp.js file, you can use the following snippet:
let result = require('oktopost-namespace').getDependencies(
__dirname,
() => {},
(root) =>
{
const calc = root.Example.calc;
});The result variable will be equal to an array of file names ordered by thier dependency priority. Starting from the
files that have no depends at all, and all the way to the enrty-point file of the project - that depends on all
other library files.
In this case result it will be equal to:
[
'src/Example/Subdir/sub.js',
'src/Example/Subdir/sum.js',
'src/Example/calc.js'
]If your project depends on any other files from different libraries, they will also be included inside this array. For example:
[
'node_modules/my_lib/src/other_file.js',
'src/Example/calc.js'
]pathmust be the full directory path toindex.jsfile.setupCallbackthis function is called before resolving dependencies. You can leave it empty for most cases.initCallbackis a function that is used to load all dependencies. In most cases this can be done by loading the entry-point object of your library. In this case it's thecalcfunction.
For more generic example, see the content of docs/example_01
git clone git@github.com:Oktopost/namespace.git
cd namespace/docs/example_01
npm install
node run_me.js
node run_me_gulp.js