Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

How can I make my JavaScript library global?

I want to create a JavaScript library and have it readily available everywhere, exactly as Moment.js does. For example, when I import Moment.js I can use it wherever I want by just typing:

moment.someMomentFunction()

Similarly, I'd want to call my function from everywhere by just doing:

mylib.function1()

mylib.function2()

etc.. 

Looking at the Moment.js source code I cannot see any reference to the window object (which is the one you should use if you want your object to be global)

Upvotes: 1

Views: 2424

Answers (2)

vaibhav mehta
vaibhav mehta

Reputation: 596

Ordinary I use something like this to define a separate module using ES5.

LibName= window.LibName || {};

LibName = function () {

  var yourVar1;
  var yourVar2;


  publicFunc1 = function() {

  };

  privateFunc2 = function() {

  };


  return {
    "publicFuncName" :  publicFunc1
  }

}();

With the help of ES6, you may create with class and without window variable.

class MyLib {
  constructor() {
    this.foo = 1;
    this.bar = 2;
  }

  myPublicMethod1() {
    return this.foo;
  }

  myPublicMethod2(foo) {
    return foo + this.bar;
  }
}

const instance = new MyLib();
export { instance as MyLib };

In code, you going to use it like this

import { MyLib } from './MyLib';

Upvotes: 0

Meiswjn
Meiswjn

Reputation: 915

EDIT: If you specifically want to create a library, export / import should help you:

import * as myModule from '/modules/my-module.js';

Export a function in the library with the export keyword:

export function bing(Parameters here) {
alert("bong");
}

As answered in Calling a javascript function in another js file

You can only call functions from files that were loaded before and are in the same scope. If the accepted answer from the refered post doesn't work, try jQuery

$.getScript(url, function() { bläh(); });

Upvotes: 1

Related Questions