ilearnio / module-alias

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

Using module-alias to resolve non-module paths #71

Open darrenrahnemoon opened 5 years ago

darrenrahnemoon commented 5 years ago

Say I have a directory that I want to resolve with module-alias. The directory doesn't have any js modules inside so I can't just do require.resolve("@storage/public"), I simply want to resolve its path using the same aliases. What should I do?

Kehrlann commented 5 years ago

Hey @darrenrahnemoon !

Currently, module-alias only supports module resolution, and the list of registered aliases is not publicly accessible. It would be trivial to expose aliased paths - but I'm not sure doing path aliasing should be part of this package.

It seems you're not the only one asking for this feature though - see #67. So I'll pull @ilearnio, the original author, for his opinion.

In the meantime, you could hack your way around by transforming your public folder into a package, with a simple index.js containing:

module.exports = __dirname;

Or, if @storage is a module itself:

module.exports.getPublicFolder = function() { return path.resolve(__dirname, "public"); }
ilearnio commented 5 years ago

@darrenrahnemoon Maybe that should have been implemented long time ago but the require.resolve was never tested for resolving paths with aliases. So it may not work not only for empty directories but for full ones as well. I'll add a separate ticket for that

Kehrlann commented 5 years ago

As I answered in #72, require.resolve does work ; however it only resolves modules.

So the question here is: do we expand module-alias to work with path.resolve ?

ilearnio commented 5 years ago

@Kehrlann Why not to use require.resolve instead of path.resolve. Like so path.readFileSync(require.resolve('~someAlias/index.js')). As for the problem discussed in #67 I think it's a misunderstanding of module-alias general concept. I left a comment to that issue

Kehrlann commented 5 years ago

AFAICT require.resolve only work for modules. So if your directory is not a module, then require.resolve will throw

Error: Cannot find module '/home/my-user/my-project/some/aliased/directory

Given the alias:

{
  "~some-alias": "some/aliased/directory"
}

We could imagine something like:

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

// Bare minimum:
const aliasedPath = ma.getPath('~some-alias'); 
// -> returns /path/to/module/some/aliased/directory

// Suggestion one:
 const one = ma.getPath('~some-alias/public'); 
// -> returns /path/to/module/some/aliased/directory/public

// Suggestion two:
const two = ma.getPath('~some-alias', 'subdir', 'public'); 
// -> returns /path/to/module/some/aliased/directory/subdir/public
ghost commented 4 years ago

@Kehrlann, that's very good! That would be very useful to use together with glob.