7

I am calling third party REST API using fetch() method in my LWC Component. Now wanted to use npm package to handle the request in LWC JS Controller.

Is there any way to include the npm package in LWC JS Controller and use in Salesforce?

I've heard that salesforce is coming up with Salesforce Evergreen service container using which we can use any other programming language in SF to write the business logic.

2 Answers 2

8

Yes, you can include the packages in lightning container and LWC Open source build. Salesforce natively does not support npm structure but most of npm packages are available as standalone .js files which can be used and loaded in Salesforce LWC components.

1
  • 3
    +1 Also, browserify can convert most npm packages to something you can import in a browser (including LWC).
    – sfdcfox
    Commented May 2, 2020 at 13:55
2

This stuff isn't well documented, but I was able to incorporate the expr-eval library by taking the following steps:

  1. Retrieve the bundled code from cdnjs (https://cdnjs.com/libraries/expr-eval/2.0.2) and paste into a new file in my LWC utility component directory, exprEval.js:
lwc
  └───formUtils
    ├──__tests__
    ├──exprEval.js
    ├──formUtils.js
    ├──formUtils.js-meta.xml
  1. At the bottom of exprEval.js, get and re-export the exports generated by the bundled code. These exports show up differently depending on whether you're running the LWC in the browser or in a Jest test, so I had to fiddle with this a bit. I ended up with:
// All lines below were added manually.
// window.exprEval works in the browser
// exports works in Node.js (Jest)
const _exprEval = window.exprEval ? window.exprEval : exports;
const { Parser, Expression } = _exprEval;
export { Parser, Expression };
  1. I also added comments at the top of exprEval.js so the next dev will have some idea how to proceed when it comes time to upgrade the dependency.
/**
 * Downloaded from https://cdnjs.com/libraries/expr-eval/2.0.2
 *
 * See manually added lines at the bottom that allow this script to be referenced
 */

I can now use the following in formUtils.js:

import { Parser } from "./exprEval";

export const evaluateExpression = (data, expression) => {
  if (!expression) return true;
  return Parser.evaluate(expression, data);
};

I'll be honest: this solution isn't all that satisfying to me. It won't handle complex dependency trees. I would like each LWC component bundle to have its own package.json, and I'd like to be able to run an NPM script to find out-of-date library versions and upgrade them across all my LWCs. But at least this works for now.

POC for a more maintainable solution, anyone?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .