hook-require-path

1.1.0 • Public • Published

hook-require-path

Module path prefix alias for node.

Quick example

// 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')

Automatic completion in VS Code

image

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')

API

addRule(prefix, dir)

prefix: String

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.

dir: String

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()

install the hook.

uninstall()

uninstall the hook.

test

npm run test
node test/install.manual-test.js

Package Sidebar

Install

npm i hook-require-path

Weekly Downloads

0

Version

1.1.0

License

MIT

Unpacked Size

158 kB

Total Files

16

Last publish

Collaborators

  • imyxz