简体   繁体   English

如何更改我自己的库的index.js,以将其作为本地对象而不是全局对象导入?

[英]How can I change my own library's index.js to import it as local object, not as global one?

Currently I have index.js file in my library. 目前,我的库中有index.js文件。

import method1 from './method1';
import method2 from './method2';

(function(window){
  window.myLib = {
    processArray,
    processString,
  }
})(window);

And if I wanna use this library, I should do like: 如果我想使用该库,我应该这样做:

import 'my-lib';
myLib.method1();

How can I refactor my index.js to not use global object and use this library like: 我如何重构我的index.js以不使用全局对象,并像下面这样使用该库:

import myLyb from 'my-lib';
myLib.method1();

I did this for a custom library of my own. 我这样做是为了自己的自定义库。

Using the modern Class syntax, assuming this file was called MyLib.js : 使用现代的Class语法,假设此文件名为MyLib.js

class MyLib {

   constructor() {
     // do stuff
   }

   // other functions that do stuff

   processArray() {

   }

   processString() {

   }

}

export default MyLib;

In your other code, such as index.js , you'd import and use your library like this: 在其他代码(例如index.js ,您将像这样导入和使用您的库:

import MyLib from './MyLib'

// later on

MyLib.processArray()
MyLib.processString()

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

相关问题 如何让 $node index.js 在我的命令行中运行 index.js? - How can I get $node index.js to run index.js in my command line? 如何将 .ejs 文件中声明的对象导出到我的 index.js - How can I export an object declared in a .ejs file to my index.js Discord.js -> 如何在 JavaScript 的 index.js 中使用 kick 命令(有自己的文件) - Discord.js -> How do I use the kick command (has it's own file) in index.js in JavaScript 如何在 react naitve 中从一个 index.js 文件中使用 require() 导出图像路径? - How can I export images path with require() from one index.js file in react naitve? 节点我的应用程序如何找到index.js - node how can My app find index.js 我如何使用Express Framework在循环中获取局部变量以更改节点js中的全局变量? - how can i get my local variable in loop to change global variable in node js using express framework ?? 如何在index.js中动态导出组件? - How can I dynamically export components in index.js? 我如何在Ubuntu中运行“ node index.js” - How can i run “node index.js” in ubuntu 如何在使用 header 作为开关位置的同时将我的亮/暗模式主题包裹在 index.js 周围? - How can I wrap my light/dark mode theme around index.js while using my header as the switch location? 不要在文件夹导入时导入“ index.js”吗? - Do not import “index.js” on folder import?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM