Error After Compiling TypeScript: Uncaught SyntaxError - Encountered an Unexpected { Token

Situation

Every time I launch my application from index.html, linking the main.js file, which has been compiled from Typescript using es6 as the target and ESNext as the module, an error pops up in the browser:

Error

main.js:3 Uncaught SyntaxError: Unexpected token {

Main.ts

    ///     IMPORTS
    //////////////////////////////////////////////////////////////////////
    import { Player }     from './classes/Player'   <= Error Found!
    import { printTable } from './helpers/Helpers'

    ///     MAIN COMMANDS
    //////////////////////////////////////////////////////////////////////
    let p1 = new Player('Bob', 'Hunter', 1, 10);

    printTable(p1);

Idea

I seem to be importing my code incorrectly, and am struggling to understand why. This method of importing exported code, classes, etc., is commonly used, so I can't figure out where I'm going wrong. Everything runs smoothly when all code is in one file, but when I try to organize it differently, issues arise.

Any advice would be greatly appreciated.

  • Thank you in advance!

Source Code

Answer №1

When utilizing ESNext as the module, an error is encountered in the browser:

main.js:3 Uncaught SyntaxError: Unexpected token {

The issue here stems from attempting to utilize ES6 import syntax in a traditional script (

<script src="index.js"></script>
). The correct usage of ES6 import and export is with modules, which are implemented in the browser using
<script type="module" src="whatever"></script>
.

Have you explored the option of incorporating Webpack? This tool can automatically compile TypeScript files into a single JavaScript bundle that can be loaded into your HTML file using just one script tag.

Answer №2

If you want to import in the manner you are currently utilizing, it is necessary to export the class reference directly, rather than within an object.

For instance:

(correct) export Player; (incorrect) export { Player }

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

Capture information and store it in a database through the use of AJAX technology

I want to implement AJAX for real-time saving of user input comments directly to the database. Here is where users can input their comments: <div class="comment"> <form action="comment.php"> <textarea cols="35" name="comment ...

Is there a way to ensure my jquery post request functions properly with the variable retrieved from a function upon clicking?

I've hit a roadblock trying to pass a game's name to my php function when a user clicks a button. The concept is simple: the user clicks a button with the video game's name as its value, then the php script checks the ranking of that game an ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Using JavaScript, append a variable to the existing URL

At the moment, I am using this JavaScript code snippet to load a URL based on the dropdown selection... var orderby = jQuery('#dropdown'); var str; orderby.change(function(){ str = jQuery(this).val(); window.lo ...

Tips for cycling through an associative array using integer indices?

No matter where I look, it seems like finding an answer to this question is impossible I've got an array array=["id1" : "somedata", "id2" : "somedata2",....] So I can access it using a special database ID, but what if I want to iterate through this ...

What are the steps to make a counter-clockwise dial with jQuery Knob?

Is there a way to use multiple instances of jQuery.countdown? Can I create countdown circles using jQuery Knob? Find examples here and here. Using Multiple instances of jQuery.countdown <div data-countdown="2016/01/01"></div> <div data-co ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

Switching the Require statement to an Import statement led to an error popping up

Currently, I am exploring the use of Ajv with typescript. import { Ajv } from "ajv"; let ajv = new Ajv({allErrors: true}); I have encountered an error and I'm unsure why it is occurring: [ts] 'Ajv' only refers to a type, but is being u ...

Apply Jquery to add emphasis to every item on the list

Can someone help me with this assignment? I need to create a jQuery function that italicizes all list elements on the page when triggered by the client. Here is my current approach: $(document).ready(function() { $("li").click(function() { ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

When the position value in three.js exceeds a certain threshold, the mesh starts to jitter uncontrollably

In search of a unique setting, I envision a universe where the gaps between meshes represent incredibly large numbers (for instance 10^15). Despite this vast distance, there is one mesh whose position (x, y, or z) quivers unsettlingly. Even after experimen ...

How to dynamically add content to VueJS/Nuxt template using Vuex state

I'm currently delving into the world of VueJS with an aspiration to construct an app that fetches content from a WordPress instance using VueJS, Nuxt and Vuex in conjunction with the WordPress REST API. I've managed to establish a connection with ...

Setting a timer that continuously increases in duration

I created a popup with a timer that needs to extend itself when it reaches zero. It currently extends for 1 day once, but then stops. Do you have any suggestions on how I can fix this issue? Thank you! // Countdown function var setInfiniteTime = ' ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

React's useState function does not update the FileReader

I've been working on extracting values from an XML file using the code below. However, I'm encountering an issue where the console always outputs 'undefined'. Can anyone help me identify where I might be going wrong? This is my JavaSc ...

The Vue and Typescript webpage is not appearing in the GAS sidemenu template

I am tasked with developing an application for Google Sides using Vue + Typescript to enhance its functionality with an extra menu feature. You can find a sample without Typescript here. The result is visible in this screenshot: https://gyazo.com/ed417ddd1 ...

Attempted to incorporate a text input into the header of every column within a table using Jquery

Struggling to have a text input appear below the header span as desired, encountering some unexpected behavior - The feature seems to not be functioning properly. I previously implemented this in C# and now need to transition it to clientside due to speci ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

CDK deployment of lambda functions does not currently support the importing of Typescript modules

I’m currently using CDK to develop my serverless application in AWS. However, I encountered an issue where the lambda function fails to import TypeScript modules as JavaScript modules post TS file compilation. As a result, I am encountering a “Module ...

Modify the content in the v-navigation-drawer upon clicking

I am currently working on a project with a v-navigation-drawer and two buttons. The first button is designed to open the drawer, while the second one should change the content of the drawer without closing it. I want the content to update instantly without ...