npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@lukecsamuel/ts-module-alias

v1.0.1

Published

Create aliases of directories and register custom module paths

Downloads

520

Readme

This package is a major refactor of ilearnio/module-alias using TypeScript. This package changes some behaviors of the original. Namely:

  1. More recently added paths take priority over existing paths during module resolution.
  2. Only the resolution paths of the immediate parent module are modified.

ts-module-alias

Create aliases of directories and register custom module paths in Node.

It also allows you to register aliases and directories that will act just like node_modules but with your own private modules, so that you can access them directly:

Install

npm i --save @lukecsamuel/ts-module-alias

Usage

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

// Aliases
"_moduleAliases": {
  "@root"      : ".",
  "@deep"      : "src/some/very/deep/directory/or/file",
  "@my_module" : "lib/some-file.js",
  "something"  : "src/foo",
}

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

Initialize the new resolution rules within a module by creating an instance and passing the current module:

import ModuleAlias from '@lukecsamuel/ts-module-alias';
new ModuleAlias();

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:

import ModuleAlias from '@lukecsamuel/ts-module-alias';
const moduleAlias = new ModuleAlias(module);

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

// Or multiple aliases
moduleAlias.addAliases({
  '@root'  : '.',
  '@client': '/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('/others')) {
    return '/others';
  }
  return '/src';
});

//
// Register custom modules directory
//
moduleAlias.addPath('/node_modules_custom');
moduleAlias.addPath('/src');

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

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.