Adding NPM module into LWC

Importing NPM module into LWC


Hi Folks,
I am back with another post. This time I will be discussing the topic of how to add an NPM module into LWC.

Although we all know that to make any 3rd party javascript work in Salesforce we need to have it into Static Resource. But I came into a strange situation wherein I had to use an npm module into LWC. 

The issue that I was facing was that the NPM module was having several dependant files which were scattered into several folders and it would have taken me ages to read through all the codes, find the dependency and create a single JS file that is uploadable to static resource.

After researching a lot got to know about the Browserify tool (webpack is also there but browserify is easy to use). Using this tool you can just let the package know which JS file is the source file and Browserify will do the magic for you and create a single js file.

Enough of talking. Now let's get to the technicalities with an example. :)

I will discuss here the example for the Contentful package (conversion of Contentful Rich Text into HTML).

Step -1: Install the NPM module to get all the files
Use this command from VSCode terminal: 
npm install --save contentful @contentful/rich-text-html-renderer

Once this command is run. You'll see one node_modules folder is created in the VSCode.


Step -2: Locate the source file that should be passed to Broserify
For this scenario the source file is 
node_modules/@contentful/rich-text-html-renderer/dist/rich-text-html-renderer.es5.js 

Step -3: Run the Browserify command
browserify node_modules/@contentful/rich-text-html-renderer/dist/rich-text-html-renderer.es5.js --standalone CONTENTFUL >  myContentful.js

On successful execution of this command, we can see that a file named myContentful.js is created.

Step -4: Uploading to Static Resouce
This new file we can upload to a static resource which will be directly accessible in LWC.
For this example I have set the Static Resource name to ContentfulHTMLRenderer

Step -5: Utilization in LWC
Use the following code in LWC to import the static resource
import Contentful from "@salesforce/resourceUrl/ContentfulHTMLRenderer";
import { loadScript } from "lightning/platformResourceLoader";

Inside connected callback load the script using following code:
connectedCallback(){
loadScript(this, Contentful)
    .then(() => {
console.log('Woohoo! Its loaded!');
}).catch((e) => {
console.log("Alas! Failed to load Contentful");
});
}

After this use the following code anywhere in the JS to convert a Contentful Rich Text into HTML
window.CONTENTFUL.documentToHtmlString(<pass the contentful rich text here>);

Comments

Popular posts from this blog