ilearnio / module-alias

Register aliases of directories and custom module paths in Node
MIT License
1.76k stars 69 forks source link

Feature request: Support for wildcards "@module-name/*": "./modules/*" #92

Closed flolu closed 4 years ago

flolu commented 4 years ago

Feature request

Instead of writing

"_moduleAliases": {
  "@module-name/moduleA": "./modules/moduleA",
  "@module-name/moduleB": "./modules/moduleB",
  "@module-name/moduleC": "./modules/moduleC",
}

it would be handy to just write:

"_moduleAliases": {
  "@module-name/*": "./modules/*"
}

@ilearnio Or is it possible to achieve this with a custom handler function?

flolu commented 4 years ago

I got it working with this implementation

const moduleAlias = require('module-alias');

const addPackageAlias = (name: string) =>
  moduleAlias.addAlias(`@module-name/${name}`, `${__dirname}../../../modules/${name}`);

const fs = require('fs');
const paths: string[] = fs.readdirSync('../../../modules');
paths.forEach(addPackageAlias);

But nevertheless, a native implementation would be appreciated :)

Kehrlann commented 4 years ago

Hey @flolu, "wildcarding" should work by default. Suppose the following package.json:

"_moduleAliases": {
  "@module-name": "base/for/your/modules"
}

You should then be able to use it this way:

require("@module-name");
require("@module-name/moduleA");
require("@module-name/some/deep/module");
flolu commented 4 years ago

@Kehrlann Sorry, it didn't work for me :disappointed: Maybe I did something wrong, not sure. You can try it by cloning this project if you want to: https://github.com/flolu/cents-ideas

Kehrlann commented 4 years ago

Oooh. This is a more complicated project, with ts-node... Can't get it to work here, running npx ts-node services/users and such. I might take a look tomorrow but can't promise anything.

Simple project: https://github.com/kehrlann/module-alias-library. It shows multiple things, but I just added an alias "wildcard" showing exactly what you mention. Run it withnode index.js`

flolu commented 4 years ago

Are there any updates on this? Still doesn't seem to work with ts-node

davestewart commented 4 years ago

Alias HQ is built around ts/jsconfig with plugins for major frameworks.

flolu commented 4 years ago

@davestewart Thanks for the tip! I've already got it working by using tsconfig-paths

Instead of running

ts-node file

I just run

ts-node -r tsconfig-paths/register file

It will automatically pick up the paths from tsconfig.json

@ilearnio @Kehrlann Should this issue be closed now?

Kehrlann commented 4 years ago

Yep, for a Typescript project, that makes a ton of sense ! Thanks for trying that out.