You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

213 lines
8.0 KiB

3 months ago
  1. # module-alias
  2. [![NPM Version][npm-image]][npm-url]
  3. If everyone who reads this would donate just $1, I would be a millionaire in 1 week! 🙃 Thank you for reaching 1M+ weekly downloads!
  4. More donations means more motivation for me to make updates. Thank you so much!
  5. [DONATE $1 ❤️](https://tinyurl.com/donate-module-alias)
  6. ---
  7. Create aliases of directories and register custom module paths in NodeJS like a boss!
  8. No more shit-coding paths in Node like so:
  9. ```js
  10. require('../../../../some/very/deep/module')
  11. ```
  12. Enough of this madness!
  13. Just create an alias and do it the right way:
  14. ```js
  15. var module = require('@deep/module')
  16. // Or ES6
  17. import module from '@deep/module'
  18. ```
  19. It also allows you to register directories that will act just like `node_modules` but with your own private modules, so that you can access them directly:
  20. ```js
  21. require('my_private_module');
  22. // Or ES6
  23. import module from 'my_private_module'
  24. ```
  25. **WARNING:** If you are going to use this package within another NPM package, please read [Using within another NPM package](#using-within-another-npm-package) first to be aware of potential caveats.
  26. ## Install
  27. ```
  28. npm i --save module-alias
  29. ```
  30. ## Usage
  31. Add your custom configuration to your `package.json` (in your application's root)
  32. ```js
  33. // Aliases
  34. "_moduleAliases": {
  35. "@root" : ".", // Application's root
  36. "@deep" : "src/some/very/deep/directory/or/file",
  37. "@my_module" : "lib/some-file.js",
  38. "something" : "src/foo", // Or without @. Actually, it could be any string
  39. }
  40. // Custom module directories, just like `node_modules` but with your private modules (optional)
  41. "_moduleDirectories": ["node_modules_custom"],
  42. ```
  43. Then add this line at the very main file of your app, before any code
  44. ```js
  45. require('module-alias/register')
  46. ```
  47. **And you're all set!** Now you can do stuff like:
  48. ```js
  49. require('something')
  50. const module = require('@root/some-module')
  51. const veryDeepModule = require('@deep/my-module')
  52. const customModule = require('my_private_module') // module from `node_modules_custom` directory
  53. // Or ES6
  54. import 'something'
  55. import module from '@root/some-module'
  56. import veryDeepModule from '@deep/my-module'
  57. import customModule from 'my_private_module' // module from `node_modules_custom` directory
  58. ```
  59. ## Advanced usage
  60. If you don't want to modify your `package.json` or you just prefer to set it all up programmatically, then the following methods are available for you:
  61. * `addAlias('alias', 'target_path')` - register a single alias
  62. * `addAliases({ 'alias': 'target_path', ... }) ` - register multiple aliases
  63. * `addPath(path)` - Register custom modules directory (like node_modules, but with your own modules)
  64. _Examples:_
  65. ```js
  66. const moduleAlias = require('module-alias')
  67. //
  68. // Register alias
  69. //
  70. moduleAlias.addAlias('@client', __dirname + '/src/client')
  71. // Or multiple aliases
  72. moduleAlias.addAliases({
  73. '@root' : __dirname,
  74. '@client': __dirname + '/src/client',
  75. ...
  76. })
  77. // Custom handler function (starting from v2.1)
  78. moduleAlias.addAlias('@src', (fromPath, request, alias) => {
  79. // fromPath - Full path of the file from which `require` was called
  80. // request - The path (first argument) that was passed into `require`
  81. // alias - The same alias that was passed as first argument to `addAlias` (`@src` in this case)
  82. // Return any custom target path for the `@src` alias depending on arguments
  83. if (fromPath.startsWith(__dirname + '/others')) return __dirname + '/others'
  84. return __dirname + '/src'
  85. })
  86. //
  87. // Register custom modules directory
  88. //
  89. moduleAlias.addPath(__dirname + '/node_modules_custom')
  90. moduleAlias.addPath(__dirname + '/src')
  91. //
  92. // Import settings from a specific package.json
  93. //
  94. moduleAlias(__dirname + '/package.json')
  95. // Or let module-alias to figure where your package.json is
  96. // located. By default it will look in the same directory
  97. // where you have your node_modules (application's root)
  98. moduleAlias()
  99. ```
  100. ## Usage with WebPack
  101. Luckily, WebPack has a built in support for aliases and custom modules directories so it's easy to make it work on the client side as well!
  102. ```js
  103. // webpack.config.js
  104. const npm_package = require('./package.json')
  105. module.exports = {
  106. entry: { ... },
  107. resolve: {
  108. root: __dirname,
  109. alias: npm_package._moduleAliases || {},
  110. modules: npm_package._moduleDirectories || [] // eg: ["node_modules", "node_modules_custom", "src"]
  111. }
  112. }
  113. ```
  114. More details on the [official documentation](https://webpack.js.org/configuration/resolve).
  115. ## Usage with Jest
  116. Unfortunately, `module-alias` itself would not work from Jest due to a custom behavior of Jest's `require`. But you can use it's own aliasing mechanism instead. The configuration can be defined either in `package.json` or `jest.config.js`. The example below is for `package.json`:
  117. ```js
  118. "jest": {
  119. "moduleNameMapper": {
  120. "@root/(.*)": "<rootDir>/$1",
  121. "@client/(.*)": "<rootDir>/src/client/$1"
  122. },
  123. }
  124. ```
  125. More details on the [official documentation](https://jestjs.io/docs/en/configuration#modulenamemapper-objectstring-string--arraystring).
  126. ## Using within another NPM package
  127. You can use `module-alias` within another NPM package, however there are a few things to take into consideration.
  128. 1. As the aliases are global, you should make sure your aliases are unique, to avoid conflicts with end-user code, or with other libraries using module-alias. For example, you could prefix your aliases with '@my-lib/', and then use require('@my-lib/deep').
  129. 2. The internal "register" mechanism may not work, you should not rely on `require('module-alias/register')` for automatic detection of `package.json` location (where you defined your aliases), as it tries to find package.json in either the current working directory of your node process, or two levels down from node_modules/module-alias. It is extremely likely that this is end-user code. So, instead, your should either register aliases manually with `moduleAlias.addAlias`, or using something like `require('module-alias')(__dirname)`.
  130. Here is an [example project](https://github.com/Kehrlann/module-alias-library).
  131. ## Known incompatibilities
  132. This module does not play well with:
  133. - Front-end JavaScript code. Module-alias is designed for server side so do not expect it to work with front-end frameworks (React, Vue, ...) as they tend to use Webpack. Use Webpack's [resolve.alias](https://webpack.js.org/configuration/resolve/#resolvealias) mechanism instead.
  134. - [Jest](https://jestjs.io), which discards node's module system entirely to use it's own module system, bypassing module-alias.
  135. - The [NCC compiler](https://github.com/zeit/ncc), as it uses WebPack under the hood without exposing properties, such as resolve.alias. It is not [something they wish to do](https://github.com/zeit/ncc/pull/460).
  136. ## How it works?
  137. In order to register an alias it modifies the internal `Module._resolveFilename` method so that when you use `require` or `import` it first checks whether the given string starts with one of the registered aliases, if so, it replaces the alias in the string with the target path of the alias.
  138. In order to register a custom modules path (`addPath`) it modifies the internal `Module._nodeModulePaths` method so that the given directory then acts like it's the `node_modules` directory.
  139. ## Refactor your code (for already existing projects)
  140. If you are using this on an existing project, you can use [relative-to-alias](https://github.com/s-yadav/relative-to-alias) to refactor your code to start using aliases.
  141. ## Donate
  142. If everyone who downloads module-alias would donate just $1, I would be a millionaire in 1 week!
  143. I love contributing to open source, for free, but you know, sometimes, in the middle of the night, I may wan to eat.
  144. There are some improvements planned for module-alias and your donations will help a lot to make it happen faster.
  145. [DONATE $1 ❤️](https://tinyurl.com/donate-module-alias) and thank you so much!
  146. [npm-image]: https://img.shields.io/npm/v/module-alias.svg
  147. [npm-url]: https://npmjs.org/package/module-alias
  148. [travis-image]: https://img.shields.io/travis/ilearnio/module-alias/master.svg
  149. [travis-url]: https://travis-ci.org/ilearnio/module-alias