
[Node.js] Alias
Library that might help you deal with Node paths
npm install require-alias
Table of Contents
#Quick example
(Of how one might use it in project)
Simple application with three files and some folders with structure like:
C:\test
- the application folder
C:\test\this\is\an\example.js
- random export of function that returns string 'foo'
module.exports = function () {
return 'foo';
};
C:\test\app.js
- the main runnable where to configure alias
var Alias = require('require-alias');
global.alias = new Alias({
aliases: {
'@root': './',
'@folder': 'this/is/an/'
}
});
alias.require('@root/random');
C:\test\random.js
- just a random file to test alias
var path = alias.path('@folder/example');
console.log(path);
var module = alias.require('@folder/example');
console.log(module());
#Full example
var Alias = require('../src/require-alias');
var exampleAlias = new Alias({
root: './app/',
aliases: {
'@models': 'models',
'@random': 'random',
'@another': 'another/path',
'@and': 'another/path'
}
});
exampleAlias.add({
'@handlers': 'handlers',
'@bar': 'models/bar'
});
exampleAlias.add('@bar', 'models/bar');
exampleAlias.delete('@random');
exampleAlias.delete(['@another', '@and']);
var pathToFoo = exampleAlias.path('@handlers/for/foo');
var foo = require(pathToFoo);
console.log(foo());
var pathToBar = exampleAlias.path('@bar');
var bar = require(pathToBar);
console.log(bar());
var moduleFoo = exampleAlias.require('@handlers/for/foo');
console.log(moduleFoo());
global.alias = exampleAlias;
alias.add('@baz', 'baz');
var baz = alias.require('@baz');
console.log(baz());
var pathToBaz = alias.path('@baz');
console.log(pathToBaz);
#API
var alias = new Alias();
alias.root.set(String)
alias.root.get()
alias.storage(String)
Returns path of given alias or the whole storage
String
(optional) - Alias (eg '@foo'
)
alias.add(String, String)
Add single alias
alias.add(Object)
Add single / multiple alias(es)
Object
- Key-value object where key is alias and value is path reference alias (eg {@foo: 'foo/bar'}
)
alias.delete(String)
Deletes single alias
String
- Alias (eg '@foo'
)
alias.delete(Array)
Deletes multiple aliases
Array
- Array of strings, each being alias (eg ['@foo', '@bar']
)
alias.path(String)
Returns path reference of alias
String
- Alias (eg '@foo'
)
alias.require(String)
Returns module export of alias
String
- Alias (eg '@foo'
)