When creating a npm package, it is quite common and convenient to structure it like so:
root
/ dist
/ src
/ package.json
where package.json
:
{
"main": "dist/index.js"
"files": [ "dist" ]
}
The drawback of this approach is, when consumer wants to require files using relative path, it needs to include the dist
folder. E.g. const abc = require('my-package/dist/x/y/abc');
Is there a way to tell NodeJS to resolve relative path based on path.dirname(main)
or something similar?
UPDATE: to clarify, this is related to relative/deep resolution, not about export hoisting in ES6. It is a controversial subject that should this be done at all, as the consumer is coupled to the internal folder structure of the package.
UPDATE 2: what I want to achieve is a concept of "sub-module" (similar to namespacing). For example, my folder structure looks like this:
root
/ dist
/ testUtil.js
/ index.js
testUtil.js
contains useful functions for testing. Since it is not used in normal use, I don't want to export them at top-level. i.e., instead of:
// index.js
export * from './testUtil'
I would do:
// index.js
import * as testUtil from './testUtil'
export { testUtil }
However, that still expose the testUtil
module namespace at top-level and it is hard to use:
// consuming.js
import { testUtil } from 'my-package'
const { funcA, funcB } = testUtil
It would be better if I can "tug" it under a relative path:
// consuming.js
import { funcA, funcB } from 'my-package/testUtil'
Currently, without solving the 'dist' issue, I have to do this instead:
// consuming.js
import { funcA, funcB } from 'my-package/dist/testUtil'