Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Freeze the template object #2826

Open
nolanlawson opened this issue May 6, 2022 · 2 comments
Open

Freeze the template object #2826

nolanlawson opened this issue May 6, 2022 · 2 comments
Labels

Comments

@nolanlawson
Copy link
Collaborator

nolanlawson commented May 6, 2022

Description

import template from './myTemplate.html'

The original intention was for the template to be an opaque object, but in practice, component authors have figured out how to manipulate it at runtime. The most common practice we see is setting the stylesheets/stylesheetToken in the render() function, e.g. to swap styles.

We should block this by freezing the template function object. The template.stylesheets array should also be frozen to avoid mutating it.

Examples that should not work

import a from './a.html'
import b from './b.html'

export class extends LightningElement {
  render() {
    a.stylesheets = b.stylesheets // should not work
    a.stylesheetToken = b.stylesheetToken // should not work
  }
}
import a from './a.html'
import b from './b.html'

export class extends LightningElement {
  render() {
    a.stylesheets.push(...b.stylesheets) // should not work
  }
}

Possible Solution

Long-term, the best solution for dynamic stylesheet modification is programmatic style injection.

In the short-term, component authors can swap templates only rather than stylesheets:

import a from './a.html'
import b from './b.html'

export class extends LightningElement {
  render() {
    if (someCondition) {
      return a
    } else {
      return b
    }
  }
}

The above example is fine. However, it may require some duplicate HTML files to associate with the CSS files that the user is trying to swap out. (In practice, people are modifying stylesheets because if they have one template but multiple stylesheets, it's cumbersome to duplicate the template HTML file for every stylesheet.)

Related:

@uip-robot-zz
Copy link

This issue has been linked to a new work item: W-11111178

@nolanlawson
Copy link
Collaborator Author

Rather than throw a runtime error, this should probably silently fail with a warning. It's better to have a page with some messed-up CSS than to completely fail with an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants