14

i am trying to alias a module however i am not sure how to do that with package.json

in webpack you would do something like this:

module.exports = {
  //...
  resolve: {
    alias: {
      'pixi.js': 'pixi.js-legacy'
    }
  }
};

But what is the equivalent without webpack?

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364
  • I have two packages `ajs` and `bjs`. One installs using `npm i ajs` and `npm i bjs`. I wish to install `bjs` when I run `npm i ajs`. Is it possible? https://stackoverflow.com/questions/72554667/install-package-x-when-a-request-for-package-y-installation-is-made – Gary Jun 13 '22 at 03:58

2 Answers2

24

Since NPM Version 6.9 of March 2019 it is supported without installing any additional packages (see the RFC):

npm i aliasName@npm:packageToInstall

⬇⬇⬇

// package.json
"dependencies": {
    "aliasName": "npm:packageToInstall@^1.6.1"
}

The idea seems to be that npm: is a URI-like scheme in a dependency version specifier.

Usage:

const alias = require( 'aliasName' );
SanBen
  • 2,581
  • 26
  • 35
  • I have two packages `ajs` and `bjs`. One installs using `npm i ajs` and `npm i bjs`. I wish to install `bjs` when I run `npm i ajs`. Is it possible? https://stackoverflow.com/questions/72554667/install-package-x-when-a-request-for-package-y-installation-is-made – Gary Jun 13 '22 at 03:58
  • This solution is not friendly if using `yalc` for dev locally. `yalc` read `aliasName` while the published one is `packageToInstall`, which doesn't match. Now my fix is to manually modify the `name` in `package.json` when doing `yalc publish`, to match the `aliasName`. – Wayne Mao Feb 09 '23 at 03:37
10

There is a npm package for this: module-alias.

After installing it you can add your aliases to the package.json, like so:

"_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
}

Make sure to add this line at the top of your app's main file:

require('module-alias/register');

You should only use this in final products (and not packages you intend to publish in npm or use elsewhere) - it modifies the behavior of require.

Mat Sz
  • 2,524
  • 1
  • 10
  • 23