繁体   English   中英

在 JavaScript 中创建服务库,如何将功能从一个文件导出到另一个文件?

[英]Creating service library in JavaScript, how to export functions from one file in another?

所以我在身份服务中有这个代码。

export function sumbitLogin(username, password) {
    console.log(username, password);
}

因此,无需在每个组件中导入我需要的每项服务,我希望能够只导入一个服务库,让我的组件可以访问它需要的每项服务。

所以我创建了一个 js 库文件,它只包含

export * as Identity from "./identity-service";

这样我就可以从我的组件中导入该文件作为

import * as Services from '../../services/service-library';

它似乎没有接受这个,因为它给了我这个错误

./src/services/service-library.js 1:9
Module parse failed: Unexpected token (1:9)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
 * ./node_modules/eslint-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
> export * as Identity from "./identity-service";

我尝试了 10 种不同的方式导出它,但我永远无法达到submitLogin() 有谁看到我错过了什么? 我觉得另一个装载机是不必要的,但如果不是,我不知道我需要哪个装载机?

更好的方法是在services文件夹中创建一个index.js文件,您可以在其中重新导出所有服务:

import * as Identity from './identity-service';
import * as Logger from './logger-service';
...

export {
  Identity,
  Logger,
};

然后您可以直接使用该文件:

import * as Services from '../services';

const { Identity, Logger } = Services;

Identity.sumbitLogin(username, password);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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