ERPNext Foundation ERPNext Cloud User Manual Blog Discuss Frappé* Donate

How to import a .js module in Frappe?


#1

I have a custom .js file attached to the main page via hooks.py and I’d like to clean it up by breaking into separate modules. Is it possible to import a .js module without adding it to the hooks.py?

I tried standard ES6 imports, but since hooks.py do not attach the .js file as type="module" I can’t use the import system. I tried using the frappe.require() function, but couldn’t figure out how it works.


#2

Okay, I figured out this one also.

You frappe.require() a script symlinked to assets/app_name/js/... folder of the site in question, then use the imported function in the provided callback. The callback is executed in the scope, containing the imported function and you can assign it to a variable you define:

var imported_helper = undefined;
frappe.require('assets/app_name/js/utils/utilities.js', () => {
    imported_helper = helper_defined_in_utilities_js;
});

imported_helper(args);

It would be lovely if the docs mentioned it somewhere :neutral_face: