I'm new to JS infrastructure, and I'm trying to understand npm
modules.
I'm creating JavaScript npm
module with several classes. Let's call it Foo
and Bar
for example, Foo
class is located in ./src/foo.js
file and Bar
class in ./src/bar.js
:
// ./src/foo.js
export default class Foo {}
and
// ./src/bar.js
export default class Bar {}
Also, I have ./src/index.js
where I want to export Foo
and Bar
to make it accessible from other modules:
import Foo from './foo.js';
import Bar from './bar.js';
What I want, is to name my module foobar
for example, and publish it to npmjs
, then install it using npm install --save foobar
from other module and import Foo
and Bar
from foobar
module:
import {Foo, Bar} from 'foobar';
var foo = new Foo();
var bar = new Bar();
What should I do with index.js
file to export Foo
and Bar
globally (on module level) to be able importing it from other module?
I'm new to JS infrastructure, and I'm trying to understand npm
modules.
I'm creating JavaScript npm
module with several classes. Let's call it Foo
and Bar
for example, Foo
class is located in ./src/foo.js
file and Bar
class in ./src/bar.js
:
// ./src/foo.js
export default class Foo {}
and
// ./src/bar.js
export default class Bar {}
Also, I have ./src/index.js
where I want to export Foo
and Bar
to make it accessible from other modules:
import Foo from './foo.js';
import Bar from './bar.js';
What I want, is to name my module foobar
for example, and publish it to npmjs
, then install it using npm install --save foobar
from other module and import Foo
and Bar
from foobar
module:
import {Foo, Bar} from 'foobar';
var foo = new Foo();
var bar = new Bar();
What should I do with index.js
file to export Foo
and Bar
globally (on module level) to be able importing it from other module?
-
you could write it like that
export { Foo, Bar }
and I think it will work well. – Shorbagy Commented Aug 18, 2019 at 13:45
2 Answers
Reset to default 5As @Federkun pointed out, you can use the following syntax:
import Foo from './foo.js'
import Bar from './bar.js'
export { Foo, Bar }
Using ECMAScript 6 Object Literal Property Value Shorthand, the above code is equivalent to the following:
import Foo from './foo.js'
import Bar from './bar.js'
export { Foo: Foo, Bar: Bar }
In your index.js
you should export what you want to expose to the clients of your packages.
import Foo from './foo.js'
import Bar from './bar.js'
export { Foo, Bar }