When exporting an enum in StencilJS with TypeScript, the error "Cannot find name..." may occur

Looking for a solution:

https://github.com/napolev/stencil-cannot-find-name

In this project, there are two main files to consider:

custom-container.tsx

import { Component, Element, State } from '@stencil/core';

@Component({
    tag: 'custom-container',
    styleUrl: 'custom-container.scss',
})
export class WebComponent {
    @Element() el!: HTMLStencilElement;
    @State() label: String = '<empty>';
    componentDidLoad() {
        document.querySelector('.button_get_anchor').addEventListener('click', () => {
            let position = '<unset>';
            position = this.el.querySelector('custom-details').getDefaultKnobEPosition();
            this.label = position;
        });
    }
    render() {
        return [
            <div class="label">{this.label}</div>,
            <custom-details></custom-details>,
            <div>
                <button class="button_get_anchor">Get Anchor</button>
            </div>
        ];
    }
}

custom-details.tsx

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

@Component({
    tag: 'custom-details',
    styleUrl: 'custom-details.scss',
})
export class WebComponent {
    render() {
        return [
            <div class="details">This is the "custom-details"</div>
        ];
    }
    @Method()
    sayHelloWorldOnConsole() {
        console.log('Hello World!');
    }
    
    @Method()
    getDefaultKnobEPosition(): Anchor {
        return Anchor.Left;
    }
    
}
export enum Anchor {
    Left = 'left',
    Center = 'center',
    Right = 'right',
}

The Issue: After running $ npm start --es5, an error occurs regarding the 'Anchor' name not being found.

[ ERROR ]  TypeScript: ./stencil-cannot-find-name/src/components.d.ts:66:39
           Cannot find name 'Anchor'.
...

You can see the error in this image:

https://i.stack.imgur.com/2iWZN.png

Moreover, Visual Studio Code also highlights this issue as shown here:

https://i.stack.imgur.com/Wer7m.png

The problematic line can be viewed at:

https://github.com/napolev/stencil-cannot-find-name/blob/master/src/components.d.ts#L66

This file is auto-generated and cannot be modified directly. Any suggestions on resolving this?

Thanks!

Answer №1

Separating the Anchor enum into its own file successfully resolves the building issue:

/src/components/custom-elements/Anchor.ts

export enum Anchor {
    Start = 'start',
    Middle = 'middle',
    End = 'end',
}

/src/components/custom-elements/custom-elements.tsx

import { Component, Method } from '@stencil/core';
import { Anchor } from './Anchor';

@Component({
    tag: 'custom-elements',
    styleUrl: 'custom-elements.scss',
})
export class WebComponent {
    render() {
        return [
            <div class="elements">This is the "custom-elements"</div>
        ];
    }
    @Method()
    sayHelloWorldOnConsole() {
        console.log('Greetings Earthlings!');
    }
    //*
    @Method()
    getDefaultPosition(): Anchor {
        return Anchor.Start;
    }
    //*/
}

Answer №2

When dealing with an automatically generated file, your options may be limited. The components.d.ts file can only be properly typechecked if it has access to the Anchor type through importation.

import {Anchor} from './custom-details';

If necessary, you can inject the Anchor type into the global scope to ensure visibility for all files in your compilation context.

custom-details.tsx

export class WebComponent {
   // ....
}

declare global {
  enum Anchor {
    Left = 'left',
    Center = 'center',
    Right = 'right'
  }
}

(<{Anchor: typeof Anchor}>window.Stencil).Anchor = {
  Left = 'left',
  Center = 'center',
  Right = 'right'
};

However, resorting to this method is strongly advised against.

This approach introduces a type and, even worse, a value into the global namespace!

If facing this issue, it is recommended to report it as a bug.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve information using Python in JavaScript

I am in the process of developing a website using Python, Javascript (JQuery), and AJAX. While I know how to initiate a Python script with Ajax, I am unsure of how to send data back to Javascript from Python. For instance, if there is an error in a form s ...

Issue with rendering images retrieved from JSON data

Struggling with displaying images in my Ionic and Angular pokedex app. The JSON file data service pulls the image paths, but only displays the file path instead of the actual image. Any ideas on what might be causing this issue? Sample snippet from the JS ...

Tips for retrieving user input and displaying it on an HTML page

I have encountered an issue with displaying user input in a table. The code for the table display is as follows: <tr ng-repeat="user in users" ng-class-even="'bg-light-grey'" ng-if="isLoading==false"> <td> ...

Guide on serving static HTML files using vanilla JavaScript and incorporating submodules

Is it possible to serve a static html file with elements defined in a javascript file using imports from submodules using vanilla JS? Or do I need bundling tools and/or other frameworks for this task? Here's an example code structure to showcase what ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Implementing long polling for private messaging in PHP's chat functionality

Can you help me with a question I have regarding my chat form on the HTML page? Here is the code for the form: <form action="../addchat.php" method="POST" enctype="multipart/form-data"> <textarea id="textarea" style="border- ...

The error at events.js:154 was not properly handled and caused an 'error' event to be thrown

Encountered an error while creating an Angular 2 application. I followed the instructions from this link to create a sample application. Upon running npm start Received the following error, events.js:154 throw er; // Unhandled 'error' even ...

Tips for removing a DOM element in Selenium using Java

Recently, I've been attempting to remove an element from a website using Selenium and Java with the xpath of the element readily available. WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]")); The specific e ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

Issue: Module failed to self-register. (When trying to use the onoff package)

Currently, I am attempting to include the "onoff" package in a JavaScript file within one of my Node.js projects. However, when I execute the JavaScript file, I encounter the following error: \node_modules\bindings\bindings.js:88 th ...

Unable to adjust the padding of a div while the Bootstrap 4 navbar is in a collapsed state on mobile devices

I am facing an issue with a fixed navbar at the top of my page. Below the navbar, I have the page content which includes a Bootstrap 4 image carousel. The problem arises on mobile devices where I need to add top-padding to the page-container (below the nav ...

Problem with extJS portal functionality

Currently, I am utilizing this particular URL for my application: . I attempted to swap out the existing chart in the third column with a bar chart and a pie chart (both of which work fine within panels and windows), but I encountered an "h is undefined" e ...

What is the method by which the asynchronous function produces the ultimate output?

Is there a way to modify a Dojo framework-created class with an asynchronous method so that it only returns the final value instead of a Promise or any other type? ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Extract images from dynamically loaded JavaScript website

I'm attempting to extract images from a webpage that is rendered using JS, but the picture links in the source code are incomplete. Here is where the images are located: <script language="javascript" type="text/javascript"> </script> < ...

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

Tips for resolving a 422 error on GitHub when attempting to create a repository using an Android device

After deleting an old repository, I attempted to create a new one which led to an error. I have been using my phone for a long time to delete and create repositories without any issues, so I'm not sure what changed today. I reached out to chat GPT fo ...

Activate a module within a Vuex action only upon dispatching

Is there a way to import a package for use in a Vuex Action only when the Action is dispatched, in order to reduce the size of my entry bundle? Here's what I've tried: export const actions = { async createNewBin(store, bin) { const fireba ...