All Projects → ilearnio → Module Alias

ilearnio / Module Alias

Licence: mit
Register aliases of directories and custom module paths in Node

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Module Alias

Pm2 Syslog
PM2 module to redirect application logs to syslog
Stars: ✭ 34 (-97.15%)
Mutual labels:  module
Vipera
Project is now called Swift template, check the link ➡️
Stars: ✭ 57 (-95.21%)
Mutual labels:  module
Annotationkit
The annotation implementation using Objective-C
Stars: ✭ 68 (-94.29%)
Mutual labels:  module
Module Federation Examples
Implementation examples of module federation , by the creators of module federation
Stars: ✭ 979 (-17.8%)
Mutual labels:  module
Modules
Modules in R
Stars: ✭ 54 (-95.47%)
Mutual labels:  module
Daggraph
Dagger dependency graph generator for Android Developers
Stars: ✭ 1,140 (-4.28%)
Mutual labels:  module
Module Project
扩展性和灵活性非常好的模块化开发框架,内置很灵活高效的模板引擎
Stars: ✭ 33 (-97.23%)
Mutual labels:  module
Css Vars Ponyfill
Client-side support for CSS custom properties (aka "CSS variables") in legacy and modern browsers
Stars: ✭ 1,166 (-2.1%)
Mutual labels:  module
Npm Compare
Compare npm packages from your terminal
Stars: ✭ 55 (-95.38%)
Mutual labels:  module
Epee React Admin Ts
🗡简洁、高效、易扩展的 React 快速开发模板,基于布局设计,纯 Hooks 开发,提供全链路类型检查及工具
Stars: ✭ 68 (-94.29%)
Mutual labels:  module
Typical
Animated typing in ~400 bytes 🐡 of JavaScript
Stars: ✭ 986 (-17.21%)
Mutual labels:  module
Antara Gaming Sdk
Komodo Gaming Software Development Kit
Stars: ✭ 51 (-95.72%)
Mutual labels:  module
Import Http
Import modules from URL instead of local node_modules
Stars: ✭ 1,150 (-3.44%)
Mutual labels:  module
Html Sass Babel Webpack Boilerplate
Webpack 4 + Babel + ES6 + SASS + HTML Modules + Livereload
Stars: ✭ 35 (-97.06%)
Mutual labels:  module
Invoice It
📃 Generate your orders or your invoices and export them in html, pdf or buffer easily.
Stars: ✭ 69 (-94.21%)
Mutual labels:  module
Swift Template
A template based module generator for Swift projects.
Stars: ✭ 34 (-97.15%)
Mutual labels:  module
Electron Progressbar
electron-progressbar provides an easy-to-use and highly customizable API to show and control progress bars on Electron applications.
Stars: ✭ 58 (-95.13%)
Mutual labels:  module
Simplenews.io
🏸 A news App,based on the RxJava 、MVP. 基于MVP、RxJava 、Android 组件化的新闻博客客户端.
Stars: ✭ 74 (-93.79%)
Mutual labels:  module
Reexport.jl
Julia macro for re-exporting one module from another
Stars: ✭ 69 (-94.21%)
Mutual labels:  module
Komada
Komada: Croatian for `pieces`, is a modular bot system including reloading modules and easy to use custom commands.
Stars: ✭ 67 (-94.37%)
Mutual labels:  module

module-alias

NPM Version Build Status

Create aliases of directories and register custom module paths in NodeJS like a boss!

No more shit-coding paths in Node like so:

require('../../../../some/very/deep/module')

Enough of this madness!

Just create an alias and do it the right way:

var module = require('@deep/module')
// Or ES6
import module from '@deep/module'

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:

require('my_private_module');
// Or ES6
import module from 'my_private_module'

WARNING: If you are going to use this package within another NPM package, please read Using within another NPM package first to be aware of potential caveats.

Install

npm i --save module-alias

Usage

Add your custom configuration to your package.json (in your application's root)

// Aliases
"_moduleAliases": {
  "@root"      : ".", // Application's root
  "@deep"      : "src/some/very/deep/directory/or/file",
  "@my_module" : "lib/some-file.js",
  "something"  : "src/foo", // Or without @. Actually, it could be any string
}

// Custom module directories, just like `node_modules` but with your private modules (optional)
"_moduleDirectories": ["node_modules_custom"],

Then add this line at the very main file of your app, before any code

require('module-alias/register')

And you're all set! Now you can do stuff like:

require('something')
const module = require('@root/some-module')
const veryDeepModule = require('@deep/my-module')
const customModule = require('my_private_module') // module from `node_modules_custom` directory

// Or ES6
import 'something'
import module from '@root/some-module'
import veryDeepModule from '@deep/my-module'
import customModule from 'my_private_module' // module from `node_modules_custom` directory

Advanced usage

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:

  • addAlias('alias', 'target_path') - register a single alias
  • addAliases({ 'alias': 'target_path', ... }) - register multiple aliases
  • addPath(path) - Register custom modules directory (like node_modules, but with your own modules)

Examples:

const moduleAlias = require('module-alias')

//
// Register alias
//
moduleAlias.addAlias('@client', __dirname + '/src/client')

// Or multiple aliases
moduleAlias.addAliases({
  '@root'  : __dirname,
  '@client': __dirname + '/src/client',
  ...
})

// Custom handler function (starting from v2.1)
moduleAlias.addAlias('@src', (fromPath, request, alias) => {
  // fromPath - Full path of the file from which `require` was called
  // request - The path (first argument) that was passed into `require`
  // alias - The same alias that was passed as first argument to `addAlias` (`@src` in this case)

  // Return any custom target path for the `@src` alias depending on arguments
  if (fromPath.startsWith(__dirname + '/others')) return __dirname + '/others'
  return __dirname + '/src'
})

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

// Or let module-alias to figure where your package.json is
// located. By default it will look in the same directory
// where you have your node_modules (application's root)
moduleAlias()

Usage with WebPack

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!

// webpack.config.js
const npm_package = require('./package.json')

module.exports = {
  entry: { ... },
  resolve: {
    root: __dirname,
    alias: npm_package._moduleAliases || {},
    modules: npm_package._moduleDirectories || [] // eg: ["node_modules", "node_modules_custom", "src"]
  }
}

More details on the official documentation.

Usage with Jest

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:

"jest": {
  "moduleNameMapper": {
    "@root/(.*)": "<rootDir>/$1",
    "@client/(.*)": "<rootDir>/src/client/$1"
  },
}

More details on the official documentation.

Using within another NPM package

You can use module-alias within another NPM package, however there are a few things to take into consideration.

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

Here is an example project.

Known incompatibilities

This module does not play well with:

  • 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 mechanism instead.
  • Jest, which discards node's module system entirely to use it's own module system, bypassing module-alias.
  • The NCC compiler, as it uses WebPack under the hood without exposing properties, such as resolve.alias. It is not something they wish to do.

How it works?

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.

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.

Refactor your code (for already existing projects)

If you are using this on an existing project, you can use relative-to-alias to refactor your code to start using aliases.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].