简体   繁体   中英

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 .

  • ../hello.js
  • ./hello.js
  • hello.js
  • ../hello
  • ./hello
  • hello

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:

  • ../hello.js -> same
  • ./hello.js -> same
  • hello.js -> ./hello.js
  • ../hello -> same
  • ./hello -> same
  • hello -> ./hello

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM