2

How to reference a custom JavaScript file in SharePoint framework project.

enter image description here

I have created "Assets" folder, and my Custom js file is inside this folder.

I can see that several articles have explained how to reference a JavaScript libraries, but no where i can find to reference our custom js file.

2

It is recommended to use TypeScript for SPFx development. If you want to use existing JavaScript file you can do a simple hack, rename your custom.js file to custom.ts file. The functionality that you want to be available from this file should be exported. consider below JS code in your custom.js

var customMessage = "Hello JS string";
export default customMessage;

Here we are exporting customMessage. You can assign JS function as well and export it from this file.

Going back to your MyDocumentsWebparts.ts file, add import for this file:

import customMessage from './Assets/JS/custom';

I can just display this string value:

<p class="ms-font-l ms-fontColor-white">${customMessage}</p>

enter image description here

now you have access to exposed functionality using customMessage variable! Build process will make sure that this import file content is included in output. This is beauty of SPFx build process -;

2

You can reference the .js file using require('file.js'). Keep in mind that its contents will be wrapped in a function so you won't be able to just call variables in functions defined in that file.

I've described the process and possible options in more detail at https://blog.mastykarz.nl/migrate-sharepoint-javascript-customizations-sharepoint-framework-reference-functions/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.