简体   繁体   中英

Export all classes for npm library 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?

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 }

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM