A Solution for Fixing Unexpected Token Import Error in Typescript

Currently, I am in the process of developing an Angular 4 theme specifically designed for Wordpress 4.8, intended to function seamlessly on Edge and Chrome browsers. During my testing phase, I encountered an issue with my test script (test.ts) which resulted in the following error:

Uncaught SyntaxError: Unexpected token import at src/test.js:1

For reference, here is the content of my tsconfig.json file located within the \src folder:

{
  "compilerOptions": {
  "module": "commonjs",
  "target": "es5",
  "moduleResolution": "node",
  "sourceMap": true,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "lib": [ "es2016", "es5", "dom"],
  "noImplicitAny": true,
  "suppressImplicitAnyIndexErrors": true
}
}

In addition, here is the configuration of tsconfig.json present at the root level:

{
  "compileOnSave": false,
  "compilerOptions": {
  "outDir": "./dist/out-tsc",
  "baseUrl": "src",
  "sourceMap": true,
  "declaration": false,
  "moduleResolution": "node",
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "target": "es5",
  "typeRoots": [
     "node_modules/@types"
     ],
  "lib": [
     "es2016",
     "dom",
     "es5"
     ]
  }
 }

The contents of my test.ts file are as follows:

import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from 
"@angular/platform-browser-dynamic/testing";
import {getTestBed} from "@angular/core/testing";

declare var _karma_: any;
declare var require: any;

_karma_.loaded = function () {};

getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

const context = require.context('./', true, /\.spec\.ts$/);

context.keys().map(context);

_karma_.start();

I am seeking advice on the optimal method to address this error. Any suggestions would be greatly appreciated.

Answer №1

There was an unexpected error with the code import in src/test.js at line 1

import statement is not being properly handled by TypeScript

Solution

Ensure that ts is successfully transpiling to JavaScript using TypeScript compiler.

The issue might be with the configuration setting. Using "module": "es6", is incorrect. It is recommended to switch to "module": "commonjs", especially when working with webpack.

Additional Resources

For a quick guide on resolving this issue, check out https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Answer №2

If you navigate to the ./app/ui directory and execute tsc -p . there, you will encounter the same issue...

The root of the problem lies in using "module": "system" in your tsconfig.json

TypeScript employs two approaches for resolving module names:

  • node - emulates how module names are resolved in NodeJS legacy

  • original strategy that ignores node_modules while traversing the folder structure searching for modules (refer to https://www.typescriptlang.org/docs/handbook/module-resolution.html for more information). The strategy can be specified using the moduleResolution compiler option. If this option is not provided, the compiler will default to node when targeting commonjs modules and classic otherwise. Therefore, in your scenario, classic resolution is utilized, causing modules from node_modules to remain undiscovered. I recommend explicitly defining the resolution in your configuration as follows:

    "moduleResolution": "node",

Does this solution resolve the issue?

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

Heres how you can define an index variable within a Primeng p-table similar to using ngFor

Seeking assistance to initialize an index variable like *ngFor="let d of sI.detail; let i = index" within my p-table <ng-template pTemplate="body" let-rowData > <tr class="text-center info"> <td&g ...

Ensuring robust type safety when using various maps and multiple enums as their keys

I am working on creating a type-safe function for retrieving values from a map. The function needs to handle specific logic in my use case, which is why I require it beyond this simple example below: enum ExampleA { A = 'A' } enum ExampleB { ...

Troubleshooting overload errors within ReactJS: tips and tricks

import React from 'react' import { Link } from 'react-scroll' import "./Protocol.css" import { ANALYTICS, TRADE, USERS, TRADERS, VOTES, ZEROES } from "../../Constants" const Protocol = () => { return ( ...

Ensure that the Promise is resolved upon the event firing, without the need for multiple event

I'm currently working on a solution where I need to handle promise resolution when an EventEmitter event occurs. In the function containing this logic, an argument is passed and added to a stack. Later, items are processed from the stack with differe ...

Converting a constant array of objects in Typescript into a typed index lookup object

const vehicles = [ { id: 'id1', name: 'bike' }, { id: 'id2', name: 'scooter' }, { id: 'id3', name: 'motorcycle' }, ] as const; type VehicleId = typeof vehicles[number]['id']; cons ...

Sporadic SSR Redirection Errors (discrepancy between request and response at the server.ts level)

Within my Spartacus/SAP Composable Storefront application, I have integrated Angular SSR (express). My goal is to execute a 301 redirect with the server-side rendering where the redirect URL is dynamically generated by fetching necessary components from an ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Obtain window dimensions using Angular when the page loads

To determine the window size upon resizing, I utilize the following code: @HostListener('window:resize', ['$event']) resizeHandler(event: any) { this.isSmallScreen = event.target.innerWidth > 600; } Is there a way to determine ...

The Jest mock is infiltrating the function logic instead of simply returning a rejected promise

The Issue at Hand I am currently working on testing the correct handling of errors when a use case function returns a rejected promise along with the appropriate status code. However, I seem to be encountering an issue where instead of getting a rejected ...

Allusion to a intricate data component

In my code, I have a model that is being represented by a class. For example, let's consider the model of a car: export class Car { public name : string; public color: string; public power : number; public service : boolean; } All c ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Ensure the box remains unchecked if it is not enabled

I have implemented a tree table in my Angular application. Below is the code snippet: <h5>Checkbox Selection</h5> <p-treeTable [value]="files5" [columns]="cols" selectionMode="checkbox" [(selection)]=&qu ...

New to TypeScript: Encounter a compilation error while launching Apollo Server and attempting to resolve a promise

Seeking assistance with starting an Apollo server in a TypeScript project utilizing Express. The code snippet for my app.ts is displayed below. Upon execution, I encounter the following error: Argument of type '(value: unknown) => void' is not ...

Error in React TypeScript: The onCreate function is causing an overload error. Specifically, overload 1 of 2, with 'props: Readonly<{}>', is creating issues

Why does it work in Javascript but show an error in TypeScript? How can I fix this? App.tsx class App extends React.Component<{}, null> { handleCreate = (data) => { console.log(data); } render() { return ( ...

Retain the previous selection in Ng-select when clearing the current value

I am attempting to retrieve the value of an ng-select field prior to it being cleared. It appears that all change events only provide the new value at this time. <ng-select [items]="importerFields" [(ngModel)]="selectedConstant[constant. ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

Navigating to a component route in Angular

I need to retrieve the routing URL of a component that is different from the current URL and save it in a service. For example, if my component is called parentComponent and contains another component called childComponent, then the URL of the child compon ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Customize behavior by dragging and dropping

I am working on implementing a particular behavior in Angular 8, using the Angular CDK Drag-Drop module. I have encountered some issues with it. Here are the code snippets: $('.dragger').draggable({ revert: "invalid", helper: function () ...

Issue with Angular 2 in Visual Studio 2013: Pressing Ctrl+K+D causes formatting to change to lowercase

Please note that while this issue is not directly related to Angular2, anyone who uses Angular2 with Visual Studio 2013 may be able to help. Whenever I use the key combination Ctrl + K + D in Visual Studio 2013, it changes HTML or Angular2 directives/mark ...