stencil icon indicating copy to clipboard operation
stencil copied to clipboard

Unable to use variables in Stencil decorators

Open cary-smith opened this issue 8 years ago • 15 comments

Stencil version:

@stencil/[email protected]

I'm submitting a:

  • [x] bug report
  • [ ] feature request
  • [ ] support request => Please do not submit support requests here, use one of these channels: https://forum.ionicframework.com/ or https://stencil-worldwide.slack.com

Current behavior:

Compiler error: ReferenceError: SOME_EVENT is not defined at eval

Expected behavior:

Should compile using the variable's value as the event name.

Related code:

import { Component,  Event, EventEmitter } from '@stencil/core';

/** Could also be a string variable imported from another file */
const SOME_EVENT = 'some-event';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.scss',
  shadow: true
})
export class MyComponent {

  @Event({eventName: SOME_EVENT})
  private someEvent:EventEmitter;

  protected componentDidLoad(){
    this.someEvent.emit(this);
  }

  render() {
    return <slot />;
  }
}

Other information:

This same bug affects nearly any configurable aspect of stencil decorators if a variable is used in place of a string. Multiple components may reference the same value and it would be preferable to write that primitive value in a single place to simplify refactoring and avoid typo errors (the bane of JS debugging).

cary-smith avatar Jan 08 '18 15:01 cary-smith

Currently the compiler is looking for String Literals within the decorators. I think you have a valid use case for why variables should be allowed. We will leave this open as a bug and will add to our roadmap. For now I would recommend using string literals.

jthoms1 avatar Jan 09 '18 14:01 jthoms1

Unfortunately I was unable to find a way to make this work with static analysis. I will be closing this issue as a won't fix.

jthoms1 avatar Apr 03 '18 15:04 jthoms1

@jthoms1 Some update about this? It's quite limiting. I'm building a UI Library using Stencil as core and consumed by React and Angular. The problem is that I want to make two different builds: one for standard web components (using Shadow DOM) and another withour Shadow DOM for using in both frameworks. I can't do this because this issue.

Ideas? Thanks in advance.

gugadev avatar Feb 01 '19 14:02 gugadev

Hi @jthoms1. It would be helpful for me too to use variables inside decorators. we build a stencil app. but in the future, we might build another app with react or something else, and consume just the components from the app. therefore, we are doing all inter-component communication with events. therefore i want to use the @Event decorator and pass the eventName as variable, so that we can share eventNames between components. Do you think it would be possible to reopen this issue and talk again about it?

Thank you very much in advance

feerglas avatar May 04 '19 13:05 feerglas

@jthoms1 a decorator is just syntactic sugar for a function that runs at a given lifecycle in a class (which is also just syntactic sugar for a constructor fundtion). A function that accepts a variable as an argument is as basic as it gets in JavaScript. This is definitely a bug, and one that should be fixed. Static analysis be damned if we can't pass a variable to a function.

pr3tori4n avatar Jun 13 '19 16:06 pr3tori4n

I agree with @pr3tori4n and others that this is worth the effort to fix.

Meanwhile...

  @Listen(Reporting.EVENT_REPORT_CHANGED, { target: 'document' })
  async reportChanged(event: CustomEvent) {
    this.reportID = event.detail;
  }

goes to

  componentDidLoad() {
    document.addEventListener(Reporting.EVENT_REPORT_CHANGED, async (event: CustomEvent)=>{
      this.reportID = event.detail;
    });
  }

JohnHardy avatar Nov 24 '19 19:11 JohnHardy

Not only it makes it harder to change event names globally, it also doesn't let you put variables inside the Component decorator which makes it harder to handle when you have some components' relations.

yairniz avatar Jan 29 '20 08:01 yairniz

I believe this is a typescript limitation not a Stencil limitation right?

valadas avatar Feb 06 '20 06:02 valadas

👍 this would be very useful

DimitarChristoff avatar Nov 03 '20 10:11 DimitarChristoff

Can this be reopened? This is an extremely limiting issue. Using strings everywhere is a recipe for disaster.

terodox avatar Nov 17 '20 14:11 terodox

Tried giving a string literal with variable/const interpolation:

@Listen("${myvariable}")

Compiles without complaining... unfortunately doesn't appear to work (at least for @Listen())

hmsoftware avatar Dec 31 '20 22:12 hmsoftware

Yes, I'm also running into this problem while trying to activate the shadow configuration on a component via a global constant. It would be very useful for decorators to receive variables.

daniel-casado avatar Jul 08 '21 18:07 daniel-casado

I reckon i could probably do this. I may give it a try if i get some time 🙂

johnjenkins avatar Jul 08 '21 18:07 johnjenkins

We are currently trying to work around this issues by extending the types of CustomEvents and Stencils Listen/Event decorators like so:

import { ListenOptions } from '@stencil/core/internal/stencil-public-runtime';

export type CustomEventType =
	| 'my-custom-event'
	| 'my-other-custom-event';

declare global {
	interface Window {
		addEventListener(type: CustomEventType, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

		removeEventListener(type: CustomEventType, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
	}

        interface HTMLElement {
		addEventListener(type: CustomEventType, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

		removeEventListener(type: CustomEventType, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
	}

	export const CustomEvent: {
		new<T>(typeArg: CustomEventType, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
	};

	declare module '@stencil/core' {
		interface ListenDecorator {
			(eventName: CustomEventType, opts?: ListenOptions): CustomMethodDecorator<any>;
		}

		export interface EventDecorator {
			(opts?: EventOptions): PropertyDecorator;
		}

		export interface EventOptions {
			eventName?: CustomEventType;
			bubbles?: boolean;
			cancelable?: boolean;
			composed?: boolean;
		}

		export declare const Listen: ListenDecorator;
		export declare const Event: EventDecorator;
	}
}

So far it looks promising. We have actual strongly typed literals and when refactoring IntelliJ gets all the usages correctly.

r3dDoX avatar Aug 04 '21 10:08 r3dDoX

@jthoms1

KonradAlbrecht-KSO avatar Jun 23 '22 13:06 KonradAlbrecht-KSO