[英]Export all classes for npm library module
I'm new to JS infrastructure, and I'm trying to understand npm
modules. 我是JS基础架构的新手,我正在尝试理解
npm
模块。 I'm creating JavaScript npm
module with several classes. 我正在创建包含多个类的JavaScript
npm
模块。 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
: 我们称之为
Foo
和Bar
, Foo
类位于./src/foo.js
文件中,而Bar
类位于./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: 另外,我有
./src/index.js
,我想导出Foo
和Bar
,以便从其他模块访问它:
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: 我想要的是将我的模块命名为
foobar
,然后将其发布到npmjs
,然后使用npm install --save foobar
从其他模块安装它,并从foobar
模块导入Foo
和Bar
:
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? 我应该怎么做
index.js
文件全局导出Foo
和Bar
(在模块级别)才能从其他模块导入它?
As @Federkun pointed out, you can use the following syntax: 正如@Federkun所指出的,您可以使用以下语法:
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: 使用ECMAScript 6 Object Literal属性值简写 ,上面的代码等效于以下内容:
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. 在
index.js
您应该将要公开的内容导出到包的客户端。
import Foo from './foo.js'
import Bar from './bar.js'
export { Foo, Bar }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.