Import/reuse code from masterPage (and other page.js)

I’m trying to reuse the functions we wrote in the masterPage.js by the export and import keywords but they don’t work. My code is as follow:

// masterPage.js 
... 
export function foo(value) { 
  return value + 1; 
} 
... 

// someOtherPage.js 
import { foo } from 'masterPage'; 
... 
$w.onReady(() => { 
  let bar = 1; 
  bar = foo(bar); 
}); 
... 

The console told me that it couldn’t find masterPage. I’ve tried these variances: master-page, wix-master-page, WixMasterPage, wixMasterPage. I’ve tried removing the {} around foo as well. None of them worked.

Is there anyway to do this and/or best practices to reuse code?

Thank you in advance! <3

Hi,
In order to import functions/variables from a js file which are located on the public folder , you should use the following code:

import {functionName} from 'public/jsFileName.js';

Make sure to export the functions / variables. Note that files that are created on the public folder are exposed, therefore it’s not recommended to put there keys and other information which you don’t want to be exposed.

I recommend following the instructions of the article- Working with Javascript in Wix Code. For backend files, check out this article.

Good luck!
Tal.

1 Like

Thanks a lot, @Tal! We couldn’t find the Public folder before, but we found it now.