For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user.
The structure of my build (output) folder is identical to src:
build
- index.js
- BaseClass.js
sublclasses
- SubClassA.js
- SubClassB.js
SubClassA
and SubClassB
both import and extend BaseClass
and are exported using module.exports
. The entry point, index.js
, consists of only two lines:
import SubClassA from './subclasses/SubClassA'
import SubClassB from './subclasses/SubClassB'
In my package.json
, the main
field is set to ./build/index.js
.
When installing the project or linking it via npm into a test project, I use the following code:
import SubClassA, SubClassB from 'my-package'
The import itself works fine, but the imported classes are being recognized as undefined. I have attempted different methods to resolve this issue, but none have been successful.
How should I properly address this?
UPDATE: After modifying index.js
to include:
import SubClassA from './subclasses/SubClassA'
import SubClassB from './subclasses/SubClassB'
module.exports = SubClassA
module.exports = SubClassB
there seems to be partial success. By importing both classes in the test project like this:
import SubClassA, SubClassB from 'my-package'
and then executing:
let sca = new SubClassA()
it turns out to actually be SubClassB
. However, if I exclude SubClassB
from the import statement, it functions normally.
UPDATE 2 - RESOLUTION:
Following the guidance provided in the comments, I made adjustments to the index.js
file as follows:
export { default as SubClassA } from './subclasses/SubClassA'
export { default as SubClassB } from './subclasses/SubClassB'
Then, in the test project, I imported it this way:
import { SubClassA, SubClassB } from 'my-project' and it worked.