Search code examples
sapui5

How do you use shims to map global thirdparty project to scoped object


In the documenation there is an example to include lodash in the project, which typically adds the variable "_" to the global scope. With AMD shims, you can map what is expected (globally) and surface this in the import.

E.g. for this:

specVersion: "1.0"
type: application
metadata:
  name: my.application
--- # Everything below this line could also be put into the ui5.yaml of a standalone extension module
specVersion: "1.0"
kind: extension
type: project-shim
metadata:
  name: my.application.thirdparty
shims:
  configurations:
    lodash: # name as defined in package.json
      specVersion: "1.0"
      type: module # Use module type
      metadata:
        name: lodash
      resources:
        configuration:
          paths:
            /resources/my/application/thirdparty/: "" # map root directory of lodash module

I was hoping to have the ability (via the shim configuration) to map window._ to what ever I've defined in my "import" (in the example below, "myLodash")

sap.ui.define([ "/resources/my/application/thirdparty/lodash"],

function(myLodash) { "use strict";

var MyController = Controller.extend("com.my.application", {
    myLodash.chunk(['a', 'b', 'c', 'd'], 2);
});

In RequireJS this would have been defined in Shim > exports


Solution

  • You can use the sap.ui.loader API to influence this. Somewhere before you import this module, like in Component.js do:

    sap.ui.loader.config({
       shim: {
         "path/to/module/myLodash": {
            exports: "_"
          }
       }
    });
    

    Then you can import it like:

    sap.ui.define(["path/to/module/myLodash"], function (myLodash) {
       "use strict";
        myLodash.chunk(...)
        ...
    });
    

    Make sure that path/to/module/myLodash leads to where your lodash module is located.

    Update

    In this blog it is explained how to consume modules directly from node_modules, which in my opinion is the better option.