Error: Protractor encountered an unexpected token while trying to import an external class

While working on my Protractor test, I encountered a syntax error on import when trying to bring an external class into the test. The strange thing is that the error only occurs at runtime, even though I am confident that I am importing and exporting the class correctly. Initially, the test worked fine when the class was part of the same project. However, now that I am referencing it from an external project, the issue arises.

SyntaxError: Unexpected token {
import { Helper } from './src/helper';
   ^

Main Project

test.ts
import { Helper, People, Groups } from 'sub-project';

describe('Test Description', () => {


 let helper: Helper;
 let people: People;
 let groups: Groups;


before(async () => {
    helper = new Helper();
    people = new People();
    groups = new Groups();

});

Sub-Project

export class Helper {

    private httpClient = new HttpClient();

    public async myFunction(): {

    }
}

app.ts

import { Helper } from './src/helper';
import { People } from './src/people';
import { Groups } from './src/groups';

export { Helper, People, Groups };

tsconfig.json

{
    "compilerOptions": {
        "outDir": "lib",
        "rootDir": ".",
        "target": "es5",
        "module": "commonjs",
        "types": [
            "chai",
            "chai-as-promised",
            "mocha"
        ]
    }
}

Answer №1

If you are looking to import a different file, here is how you can export a class in TypeScript:

//    index2.ts

export class user {

    display(name) {

        return `Welcome ${name}`;

    }

}

To import a class from a specific file:

 //core2.ts

import { user } from './index2'

const a = new user();

console.log(a.display(`Bharath`));

You can find more information at https://www.typescriptlang.org/docs/handbook/modules.html

Your IDE will suggest what can be imported from the specified file. Use ctrl - space to see the recommendations.

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

Monitor a universal function category

Trying to implement a TypeScript function that takes a single-argument function and returns a modified version of it with the argument wrapped in an object. However, struggling to keep track of the original function's generics: // ts v4.5.5 t ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

The SpinButton object has an undefined public property called 'value' and the public method 'focus()' is not available

Recently, I've delved into using reactjs, typescript, and Office UI Fabric. However, I'm facing a challenge with one of the components from fabric. In this scenario, I have a simple Product component containing a SpinButton and a DefaultButton. M ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

What is the method for retrieving the second type of property from an array of objects?

I have a collection of objects that map other objects with unique identifiers (id) and names (name). My goal is to retrieve the name corresponding to a specific id. Here is my initial approach: const obj = { foo: { id: 1, name: 'one' }, ...

One important rule to remember when using React Hooks is that they must be called consistently and in the correct order in each render of the component. It

Encountering an issue while trying to use the ternary operator to determine which React Hook to utilize. The error message states: "React Hook "useIsolationDynamicPhase" is called conditionally. React Hooks must be invoked in the same order during every co ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Having trouble receiving a blob response using HttpClient POST request in Angular 9?

I'm encountering an issue while attempting to receive a zip file as a blob from an HTTP POST request. However, the resolved post method overload is not what I expected. const options = { responseType: 'blob' as const }; Observable<Blob ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Images in the Ionic app are failing to display certain asset files

Currently, I am working on an Ionic 4 app for both Android and iOS platforms. The issue I am facing is that only SVG format images are displaying in the slide menu, even though I have images in both SVG and PNG formats. public appPages = [ { ...

A guide on resolving deprecated warnings for typographical errors

Every time I try to npm install I am bombarded with numerous errors. typings WARN deprecated 9/9/2016: "registry:dt/node#6.0.0+20160831021119" is deprecated (updated, replaced or removed) My experiences with typescript have been nothing but a series ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

What is the easiest way to compile a single .ts file in my src folder? I can achieve this by configuring the tsconfig.js file and running the yarn

{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, ...

Dealing with a Typescript challenge of iterating over a tuple array to extract particular values

I am struggling with writing a function that extracts names from an array of tuples, where each tuple includes a name and an age. My current attempt looks like this: type someTuple = [string, number] function names(namesAndAges: someTuple[]) { let allNa ...