This stuff isn't well documented, but I was able to incorporate the expr-eval library by taking the following steps:
- 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
- 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 };
- 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?