module-alias
Allows to register aliases of directories and custom module paths in NodeJS.
This package is highly inspired by app-module-path package and it's totally backwards compatible with it. The main difference is that this package also allows creating aliases of directories for further usage with require
/import
Install
npm i --save module-alias
Usage
Add these lines to your package.json (in your application's root)
"_moduleDirectories": ["node_modules_custom"],
"_moduleAliases": {
"@root" : "",
"@client" : "src/client",
"@admin" : "src/client/admin",
"@deep" : "src/some/very/deep/directory",
"@my_module" : "src/some-file.js",
"something" : "src/foo",
}
And these line at the very main file of your app, before any code
import 'module-alias/register'
import 'something'
import module from '@root/some-module'
import veryDeepModule from '@bar/my-module'
import myModule from '@my_module'
Advanced usage
import moduleAlias from 'module-alias'
moduleAlias.addAlias('@client', __dirname + '/src/client')
moduleAlias.addAliases({
'@root' : __dirname,
'@client': __dirname + '/src/client',
...
})
moduleAlias.addPath(__dirname + '/node_modules_custom')
moduleAlias.addPath(__dirname + '/src')
moduleAlias(__dirname + '/package.json')
moduleAlias()
Usage with WebPack
const npm_package = require('./package.json')
module.exports = {
entry: { ... },
resolve: {
root: __dirname,
alias: npm_package._moduleAliases || {},
extensions: ['', '.js', '.jsx'],
modulesDirectories: npm_package._moduleDirectories || []
}
}
How it works?
In order to register a custom modules path (addPath
) it modifies the internal Module._nodeModulePaths
method so that the directory then acts like it's the node_modules
directory.
In order to register an alias it modifies the internal Module._resolveFilename
method so that when you fire require
or import
it first checks whether the given string starts with one of the registered aliases, if so, it then replaces the alias in the string with the target path of the alias
Tags
Require alias, node import alias, node custom module directory, node local require paths, register module directory in nodejs