0

I'd like to loadScript(MyLib) with type=modules to getting import instead sharing via window. is it possible to do that? loadScript(MyLib) is loaded as native type=text/application. but i'd like to inject as <script type=modules />

import CalendarBuild from '@salesforce/resourceUrl/CalendarBuild';


    connectedCallback() {

        Promise.all([
            loadScript(this, CalendarBuild),
        ])
        .then(() => {
            const calendarEl = this.template.querySelector('div.calendar-root');
            CalendarBuild.renderCalendar(calendarEl, {
                events: [],
                unFilterEvents: [],
                locationId: "locationId",
                isFetching: false,
                defaultDate: new Date(),
                handleChangeLocation: () => {},
                handleChangeLocationSetting: () => {},
                refetchLessonsOnCalendar: () => {},
            });
        })
        .catch(error => {
            console.log('---error when init---', error?.message);
        })

1 Answer 1

1

The original solution you're asking for simply isn't possible. Locker Service (LS) and Lightning Web Security (LWS) are both designed to block script tags from loading or executing by all the usual means you'd do so on the open web. This is a security feature designed to prevent rogue scripts from going outside the security sandbox.

That said, if you want to use the code as a module, just do so as a service component. To do this, create a new component bundle, e.g. calendarBuild, and within it, populate calendarBuild.js with the entire source code from the library you want to include, including any export statements.

At this point, you should be able to import it as a regular module:

import CalendarBuild from 'c/calendarBuild';

Note that in order for this to work, you'll still need to define the component selected by this.template.querySelector('div.calendar-root'); with the lwc:dom="manual" attribute:

<div lwc:dom="manual"></div>

This element must not contain any content, as shown above.

2
  • Do you have any sample code for this, I'm not familiar so not really got this solution
    – vctqs1
    Commented Jan 3 at 10:56
  • @vctqs1 See the documentation for more information. The code in my answer is the sample code. It's literally just creating a new component, putting the JS inside the component's JS, and then importing it. You can then call the method in the renderedCallback life cycle handler.
    – sfdcfox
    Commented Jan 3 at 11:20

You must log in to answer this question.

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