Search code examples
javascriptangularjswebpackecmascript-6javascript-objects

How to call global function from controller class in AngularJs component


In app.module.js file, import JS file from external lib

import 'assets/scripts/admin';

with global function:

function anonymousAdmin() {
  "use strict";

  implementation();
}

Now in app.component.js file have controller with function call:

export const AppComponent = {
  controller: class AppComponent {
    $onInit() {
      /* global anonymousAdmin */
      anonymousAdmin();
    }
  }
};

Run Webpack/Babel to save all files (ES6) into one file (ES5). Unfortunately i have error in console:

ReferenceError: anonymousAdmin is not defined

Someone knows how I can call this function in the controller?


Solution

  • anonymousAdmin is not global function. The file is imported as ES module, and ES modules force strict mode that prevents them from leaking variables to global scope.

    It should be explicitly defined as a global:

    function anonymousAdmin() {...}
    
    window.anonymousAdmin = anonymousAdmin;
    

    If the file belongs to third-party module that cannot be directly edited, and considering that Webpack is being used, the latter can be configured to expose a variable from file ES module export with exports loader, something like:

    ...
    module: {
      rules: [
        {
          test: require.resolve('assets/scripts/admin'),
          use: 'exports-loader?anonymousAdmin'
        }
      ]
    },
    ...
    

    And the function is being imported like:

    import { anonymousAdmin } from 'assets/scripts/admin';