In this blog post, you’ll:
New to Lightning Components? Check out the Lightning Component Basics module on Trailhead.
Lightning Locker Service
window object, on the page.
Components saved with API version of 40.0 or later have Lightning Locker Service enabled and enforced automatically.
Sharing Code Securely
The helper file is specifically designed for sharing code within a single component bundle for use by the controller and renderer files. To access the shared code of the helper.js file, reference the helper argument passed to the functions in your controller.js and renderer.js files as shown in this gist.
If your need is to share code only within the component bundle itself, using the helper.js file is the recommended approach.
If your use case is to share code among a broader number of components, then you need a different solution than the helper.js resource, as outlined in the next approach.
<ltng:require> tag to make the custom functions available to all your components on the page as shown in this gist.
Note that this approach relies on modifying the prototype of the
If your need is to use code from a third-party library by one or more components, loading a static resource is the recommended approach.
If your need is to use your own shared functions or to simply modularize your component code base, although the static resource approach will work, I’d recommend the next approach using component composition.
Another approach to share code among multiple components is “service components”. No, we’re not talking about the Service Console, but rather components purposefully developed with no visual markup and instead define
Adding two numbers is a trivial example. A couple examples of more practical service components that I’m fond of are:
If you find yourself copying and pasting code into multiple components, this may be a good indicator to move the common code out to one or more service components to reduce duplication and improve maintainability by following DRY principles.
Per the documentation,
For example, the attempt by SharedLibrary.js to define a custom function
window.sum would be blocked and when your components try to call the
window.sum function they’d receive an error about an attempt to use an undefined function.
- Security for Lightning Components
- Work with Objects, Classes, and Prototypical Inheritance
- Modularizing Code in Lightning Components
- Implement and Use Lightning Service Components
- Locker Service and Lightning Container Component: Securely Using Third-Party Libraries in Lightning Components
- Winter ’19 Release Highlights
- Winter ’19 Release Notes