Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export all classes for npm library module

Tags:

javascript

npm

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?

like image 368
Kirill Avatar asked Jun 22 '26 02:06

Kirill


1 Answers

As @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 }
like image 187
user1984 Avatar answered Jun 25 '26 08:06

user1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!