Skip to content

Freeze the template object #2826

Open
Open
@nolanlawson

Description

@nolanlawson

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:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions