Module path prefix alias for node.
// index.js
const HookRequirePath = require('hook-require-path')
const hookRequirePath = new HookRequirePath()
hookRequirePath.addRule('@', '.')
hookRequirePath.addRule('~', './src')
hookRequirePath.install()
// require a module located at ./module-a
const moduleA = require('@/module-a')
//require a module located at ./src/module-b
const moduleB = require('~/module-b')
// src/module-b.js
// Once install in project entry, alias could be used in required module without install again.
module.exports = require('@/module-a') //same as require('../module-a')
It is possible to enable automatic completion when using alias
Create a file jsconfig.json
in your project root directory, and add following options
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"],
"@/*": ["./*"]
}
}
}
Example above is for following rules, you should modify it according to your rules.
hookRequirePath.addRule('@', '.')
hookRequirePath.addRule('~', './src')
the alias. would only match the prefix
following by /
.
For example, if prefix is @@
, then would match the path @@/path/to/module
, but @@path/to/module
would not be matched.
the corresponding path.
If dir
is not an absolute path, it use the project entry file path as the workdir.
if (!path.isAbsolute(dir)) {
dir = path.resolve(path.dirname(require.main.filename), dir)
}
install the hook.
uninstall the hook.
npm run test
node test/install.manual-test.js