在NPM作用域包中公开两个(或更多)Node.js Babel类
我有一个公共范围的包中的两个Node.js Babel类,并希望将它们公开。
公共范围的NPM中的类:
Index.js
export default class Index { constructor() { console.log("abc!"); } }
SecondClass.js
export default class SecondClass { constructor() { console.log("SecondClass! SecondClass!! SecondClass!!!"); } }
在公共范围的NPM中,我只能设置一个主文件:
"main": "./dist/index.js",
而在使用项目,我试图导入他们,但我失败了!
import { Index, SecondClass } from '@my-scope/my-package'; new Index(); new SecondClass();
依赖关系:
"devDependencies": { "babel-cli": "^6.26.0", "babel-preset-es2015": "^6.24.1" }
我该怎么做? 我能以某种方式做到吗?
更新1:即使使用包中的files
没有工作,使情况变得更糟,一旦我使用它,所有的JS
文件都没有了,当我在用法项目中安装我的范围包。
"files": [ "./dist/index.js", "./dist/SecondClass.js" ],
更新2:我试图使用"files":[ ... ]
如前所述,一旦我无法find任何解决方法,我在NPM Github发布了一个问题: https : //github.com/npm / NPM /问题/ 18481
经过许多小时的研究,我能够find一个解决方法,使用香草代码,但保持巴别塔的使用。
对于您的作用域NPM包中的主要JS文件,例如index.js
您必须导出所有类,如:
import SecondClass from './SecondClass'; import ThirdClass from './ThirdClass'; export { SecondClass, ThirdClass };
在您的使用项目中,您可以导入像:
import { SecondClass, ThirdClass } from '@my-scope/my-package'; new SecondClass(); new ThirdClass();
你的scoped NPM包中的package.json只需要显示index.js
比如"main": "./dist/index.js"
index.js
"main": "./dist/index.js"
。
依赖和版本:
- “babel-cli”:“^ 6.26.0”
- “babel-preset-es2015”:“^ 6.24.1”
- $ npm -v:3.10.10
- $ node -v:v6.11.3
常用的方法是创build一个名为index.js的文件,使其重新导出文件夹中的不同模块:
/src /foo.js /bar.js /index.js // index.js export * from './foo'; export * from 'bar';
这将允许您直接从文件夹而不是特定文件导入。
import {foo, bar} from './src';
这是可能的,试试这个:
Index.js
import SecondClass from './SecondClass'; class Index { constructor() { console.log("abc!"); } } export { Index, SecondClass };
用法
import { Index, SecondClass } from '@my-scope/my-package'; new Index(); new SecondClass();