Search code examples
lazy-loadingnetsuitesuitescript2.0

Loading custom module base on context in server side SuiteScript 2.0


I'm trying to load my custom module base on the condition.

CustomModule.js

define([], function(){
  export {
    run: function(){ log.debug('run in CustomModule' }
  };
}

And here is my user event script

userevent.js

define(['N/record'], function(record){
  ...
  var moduleName = record.getValue('custom_module_name'); // will return CustomModule.js
  require([moduleName], function(customModule){
    customModule.run();
  });
});

But I got following error

{
   type: "error.SuiteScriptModuleLoaderError",
   name: "INCORRECT_SUITESCRIPT_CONFIGURATION",
   message: "Incorrect SuiteScript configuration for module: CustomModule.js",
}

When I using preload like define(['CustomModule.js'), function(customModule){...}) is working, but this might not suitable for our scenario.

Any suggestion?


Solution

  • You can only include modules supported by both client and server in the define function.

    To include functionality which utilizes server-side modules, write the server side function to include a parameter for the required module, and pass the module when calling the function.

    For example, if you are calling a common function from a Suitelet, and your common function uses serverWidget, design the function to take serverWidget as a parameter or as a property of the object you're passing in.

    // sample server-side function definition included in your custom module
    const buildSublist = (scriptContext, serverWidget, sublistData)=>{
      // Make use of NetSuite server-side modules.
      // Only call this function from server-side contexts.
    };