最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Export all classes for npm library module - Stack Overflow

programmeradmin6浏览0评论

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?

Share Improve this question edited Aug 18, 2019 at 15:19 Kirill asked Aug 18, 2019 at 13:42 KirillKirill 8,3519 gold badges53 silver badges108 bronze badges 1
  • you could write it like that export { Foo, Bar } and I think it will work well. – Shorbagy Commented Aug 18, 2019 at 13:45
Add a ment  | 

2 Answers 2

Reset to default 5

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 }
发布评论

评论列表(0)

  1. 暂无评论