2

Is there a package.json property that can be used to specify the root folder that module resolution should start?

For example suppose we have an install in node_modules/mypackage/src/file1. And all the files we want to import start under the src directory. Can we specify something like:

 { 
    root: ./src/
 }

And then require('mypackage/file1');

Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • No... but you could make your own function to do that. – Get Off My Lawn Jul 12 '18 at 20:18
  • 1
    No, there is no property that can specify that. Why don't you just `exports.foo = require('./src/file1')` in `mypackage/index.js`? and `require('mypackage').foo`? – Patrick Roberts Jul 12 '18 at 20:18
  • I could do that. I was considering creating a index.ts and just compiling that into target. I have a lot of files: https://github.com/fireflysemantics/validator ... The other option would be to compile everything to target and copy package.json to target as well, and then publish that ... Thanks for the heads up though. – Ole Jul 12 '18 at 20:22
  • Created a feature request. Please vote for it / thumbs it up if you like the idea: https://github.com/nodejs/node/issues/21787 – Ole Jul 12 '18 at 21:03
  • @Ole I don't think node even handles requests like that, pretty sure that would fall under the responsibility of `npm` and other package managers... – Patrick Roberts Jul 12 '18 at 22:36
  • @PatrickRoberts Node ultimately has to resolve the 'require()' statement so lets keep our fingers crossed ... – Ole Jul 12 '18 at 22:38

1 Answers1

3

ECMAScript modules support an experimental exports property in package.json. You can try something like:

{
  "exports": {
    "./": "./src/"
  }
}

Then imports like:

import file1Module from 'mypackage/file1'

Should load from ./node_modules/mypackage/src/file1.js. If its not possible to alias the root you would have to do:

{
  "exports": {
    "./file1": "./src/file1.js"
  }
}

For every module or directory you wanted to alias.

As noted on your GitHub issue.

morganney
  • 6,566
  • 1
  • 24
  • 35