ThomasReggi
ThomasReggi

Reputation: 59475

Cleaning package.json "main" for use with require

I'd like to keep the path relative and always have it prepended with leading directory.

Let's say I have a string hello. It's perfectly valid to have hello in your package.main in reference to ./hello.js. However if you take hello and require it, it will look for the hello node_module and not the file. How can I prefix hello with ./ using path? The problem is that the package.json main can have these valid options. I'm not saying that these all point to the same files. I'm saying that hello.js and hello can't be put directly into require.

How can I clean all of these paths so that they work with require?

path.join gets rid of leading paths, so that doesn't work. path.resolve on the other hand does work to clean all of these paths for use with require, however it makes it into an absolute path.

Expected behavior:

Should I just create a regex to look at the path? How can I ensure it would work cross-platform?

var pkg = require('./package.json')
// var mainPackage = cleanMain(pkg.main)
// var main = require(mainPackage)

Upvotes: 1

Views: 88

Answers (1)

greim
greim

Reputation: 9437

Require paths in node only use forward slashes /, even on Windows, so that removes one piece of complexity. Beyond that, the difference between it looking in node_modules and looking up a path is whether it starts with a . or /. (Docs.) The clean function could be a simple regex test like this:

function clean(s) {
  if (!/^[\.\/]/.test(s)) {
    s = './' + s;
  }
  return s;
}

Upvotes: 2

Related Questions