module-alias icon indicating copy to clipboard operation
module-alias copied to clipboard

Using module-alias to resolve non-module paths

Open darrenrahnemoon opened this issue 5 years ago • 6 comments

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?

darrenrahnemoon avatar Sep 23 '19 18:09 darrenrahnemoon

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"); }

Kehrlann avatar Sep 24 '19 06:09 Kehrlann

@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

ilearnio avatar Sep 24 '19 07:09 ilearnio

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 ?

Kehrlann avatar Sep 24 '19 15:09 Kehrlann

@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

ilearnio avatar Sep 25 '19 09:09 ilearnio

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

Kehrlann avatar Sep 25 '19 15:09 Kehrlann

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

ghost avatar Sep 25 '20 03:09 ghost