Expose Two (or More) Node.js Babel Classes In A Npm Scoped Package
I have two Node.js Babel classes in a public scoped package and want to expose them both. Classes in the public scoped NPM: Index.js export default class Index { constructor()
Solution 1:
After many hours researching I was able to find a workaround using vanilla code but keeping the Babel usage.
For the main JS file in your scoped NPM package e.g. index.js
you must export all classes like:
importSecondClassfrom'./SecondClass';
importThirdClassfrom'./ThirdClass';
export {
SecondClass,
ThirdClass
};
And in your usage project you can import like:
import { SecondClass, ThirdClass } from'@my-scope/my-package';
newSecondClass();
newThirdClass();
The package.json from your scoped NPM package only need to expose the index.js
like "main": "./dist/index.js"
.
Dependencies and versions:
- "babel-cli": "^6.26.0"
- "babel-preset-es2015": "^6.24.1"
- $ npm -v: 3.10.10
- $ node -v: v6.11.3
Solution 2:
The common approach is to create a file named index.js such that it reexports the different modules in the folder:
/src
/foo.js
/bar.js
/index.js
// index.js
export * from './foo';
export * from 'bar';
This will allow you to import directly from the folder instead of an specific file.
import {foo, bar} from'./src';
Solution 3:
It is possible, try this:
Index.js
importSecondClassfrom'./SecondClass';
classIndex {
constructor() {
console.log("abc!");
}
}
export { Index, SecondClass };
Usage
import { Index, SecondClass } from'@my-scope/my-package';
newIndex();
newSecondClass();
Post a Comment for "Expose Two (or More) Node.js Babel Classes In A Npm Scoped Package"