Search code examples
javascriptpluginsnativescriptrequire

How to require plugins once and access it globally?


My app was made before the Nativescript CLI v5.x and got to a point where I needed to update CLI versions. The CLI version 5.4.2 suggests to add "tns-core-modules/" for every 'require' I have in my app since short import is deprecated in v5.2.0, since I have tons of plugins required on tons of pages, it's quite a pain in the ass changing every require line. How can I require all my plugins once and then use them on every page or anywhere I need it?


Solution

  • In javascript you have access to an object that always exists in the global scope, this global object provides variables and functions, the goal is to add your library to it. You have the window object for example in a browser.

    Find the global object (look post here) on your project and add your library to this object like :

    var myLib = require('myLib');
    
    var globalObject = Function('return this')();
    globalObject.myLib = myLib;