function init(options) {
if (typeof options === 'string') {
options = { base: options }
}
options = options || {}
// There is probably 99% chance that the project root directory in located
// above the node_modules directory
var base = nodePath.resolve(
options.base || nodePath.join(__dirname, '../..')
)
try {
var npmPackage = require(base + '/package.json')
} catch (e) {
// Do nothing
}
if (typeof npmPackage !== 'object') {
throw Error('Unable to read ' + base + '/package.json')
}
//
// Import aliases
//
var aliases = npmPackage._moduleAliases || {}
for (var alias in aliases) {
if (aliases[alias][0] !== '/') {
aliases[alias] = nodePath.join(base, aliases[alias])
}
}
addAliases(aliases)
//
// Register custom module directories (like node_modules)
//
if (npmPackage._moduleDirectories instanceof Array) {
npmPackage._moduleDirectories.forEach(function (dir) {
if (dir === 'node_modules') return
var modulePath = nodePath.join(base, dir)
addPath(modulePath)
})
}
}n/a
function addAlias(alias, target) {
moduleAliases[alias] = target
}...
_Examples:_
```js
const moduleAlias = require('module-alias')
//
// Register alias
//
moduleAlias.addAlias('@client', __dirname + '/src/client')
// Or multiple aliases
moduleAlias.addAliases({
'@root' : __dirname,
'@client': __dirname + '/src/client',
...
})
...function addAliases(aliases) {
for (var alias in aliases) {
addAlias(alias, aliases[alias])
}
}...
//
// Register alias
//
moduleAlias.addAlias('@client', __dirname + '/src/client')
// Or multiple aliases
moduleAlias.addAliases({
'@root' : __dirname,
'@client': __dirname + '/src/client',
...
})
//
// Register custom modules directory
...function addPath(path) {
var parent
path = nodePath.normalize(path)
if (modulePaths.indexOf(path) === -1) {
modulePaths.push(path)
// Enable the search path for the current top-level module
addPathHelper(path, require.main.paths)
parent = module.parent
// Also modify the paths of the module that was used to load the
// app-module-paths module and all of it's parents
while (parent && parent !== require.main) {
addPathHelper(path, parent.paths)
parent = parent.parent
}
}
}...
'@client': __dirname + '/src/client',
...
})
//
// Register custom modules directory
//
moduleAlias.addPath(__dirname + '/node_modules_custom')
moduleAlias.addPath(__dirname + '/src')
//
// Import settings from a specific package.json
//
moduleAlias(__dirname + '/package.json')
...function isPathMatchesAlias(path, alias) {
// Matching /^alias(\/|$)/
if (path.indexOf(alias) === 0) {
if (path.length === alias.length) return true
if (path[alias.length] === '/') return true
}
return false
}n/a
function reset() {
// Reset all changes in paths caused by addPath function
modulePaths.forEach(function (path) {
removePathHelper(path, require.main.paths)
var parent = module.parent
while (parent && parent !== require.main) {
removePathHelper(path, parent.paths)
parent = parent.parent
}
})
modulePaths = []
moduleAliases = {}
}n/a