typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6.

Here is an interface I'm attempting to export in a file named transformedRowInterface.ts:

export interface TransformedRow  {
  id: number;
  title: string;
  summary: string;
  body: string;
  synopsis: string;
  author: object;
  impressions: number;
  created: number;
  updated: number;
}

And here is my attempt to import it in a file called newsArticleModel.ts:

const appRoot = require("app-root-path");

import { TransformedRow } from "./transformedRowInterface";
// encountering the following error:
// [Node] /newsArticleModel.ts:2
// [Node] import { TransformedRow } from "./transformedRowInterface";
//SyntaxError: Unexpected token import
// also tried using require, which resulted in another error:
// const transformedRow = require(appRoot + "/src/controllers/transformedRowInterface.ts");
// triggering this error: 
// [Node] (function (exports, require, module, __filename, __dirname) { export interface TransformedRow  {
//   [Node]                                                               ^^^^^^
//   [Node]
//   [Node] SyntaxError: Unexpected token export

This is my tsconfig:

    {
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017",
    "noImplicitAny": false,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      // "*": ["node_modules/*", "src/types/*"]
    }
  },
  "include": ["src/**/*"]
}

Can anyone spot what I might be doing incorrectly?

Answer №1

I believe the reason for this issue is due to your use of ES2017, which includes native support for import syntax, resulting in output that includes:

import { thing } from './wotsit';

If your environment does not support this type of import, you may need to compile down to ES5 to transform the import into a CommonJS require call.

You can verify my hypothesis by examining the generated JavaScript code to confirm the appearance of the import statement.

Answer №2

(function (exports, require, module, __filename, __dirname) { export})

SyntaxError: Unexpected token export.

If you're encountering the same issue, perhaps you're running 'node .ts' instead of 'node .js'

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

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

Is it simple to host a vue.js web application within the assets folder of a sails.js project?

Currently, I am in the process of learning how to utilize Sails.js and vue.js. My goal is to develop a small application where a vue.js application is situated within the assets/ directory of Sails.js. The challenge I'm facing is figuring out how to s ...

Is there a method available for us to successfully deliver an email to the user who has been registered?

I am currently working on the registration page for my React app. One of the requirements is to send a confirmation email to the user's email address once they have registered. The user's account will only be confirmed once they click on the veri ...

Adjust the jQuery resizable handlers on the fly

I am encountering an issue when attempting to change the handler on a resizable element. Initially, I used : $(line) .draggable({containment:"parent"}) .resizable({ containment:"parent", handles: "e, w" }); N ...

Is there a way to achieve a XNOR-like response with necessary input?

I'm currently working with a form that looks like this: <form> <input type="text" name="input1"> <input type="text" name="input2"> <button type="submit"> ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

A function that retrieves an array containing elements that exceed a specified number and a given array

Is there a way to create a function that takes an array and a number as parameters, then returns a new array with only the elements from the original array that are greater than the given number? For example: [10, 25, 16, -5, 30, 15, 24] , 16 The output ...

Complete a form when a link or button on the webpage is clicked

I have a variety of links and buttons on my webpage, and they are generated dynamically. I am unable to assign an onclick event to each one individually. My goal is to submit form data to the next page whenever any link or button on the page is clicked. ...

Inadequate completion of Object.create() method

Here's the code snippet: //Note: x is being pulled from an external source and contains certain values var x = [{ name: 'Michael Lovesllamas Lankford', created: 1338420951.11, laptop: 'pc', laptop_version: null, userid: &apos ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

Is it possible to postpone sending a message on Discord until a certain event has been successfully completed?

After the User leaves the Discord, I attempted to create a RichEmbed Message that would include a random GIF from Giphy. The GIF was meant to be generated using the getGiphyPic() function with the help of this node module: https://github.com/risan/giphy-ra ...

Error encountered: Unexpected character 'u' found at the start of JSON parsing. Position 0

Looking for guidance on writing jest test cases for a submit function that involves JSON.parse. The code and test case are provided below. handleFormSubmit = (e) => { e.preventDefault(); let requestData = JSON.parse ...

I need help setting up the right configuration for a custom directory of Nuxt.js components. What should

<h1>Greetings everyone</h1> Currently, I'm in the process of learning how to utilize nuxt.js and have an inquiry regarding the utilization of custom directories that differ from the standard structure of a nuxt.js application. The proble ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...

Protractor: The top tool for testing AngularJS applications

Protractor is a comprehensive testing framework designed specifically for Angular applications, utilizing WebDriverJS as its foundation. As someone who is just beginning to explore web testing, I am curious about the benefits of choosing Protractor over u ...

JavaScript API Response - conditional statement for handling a 'null' response

Does anyone have any suggestions for the following scenario: I have a response in .json format containing personal data of a person, who may or may not be assigned to a project. Here is an example response where the person is not assigned to a project: & ...

Tips for resolving the error message "An issue occurred with the skill's response" within the Alexa Developer Console

Looking to develop a basic Alexa app where users can interact with voice commands, but encountering an issue with the response in the Test tab of Alexa Developer Console. The error message states "There was a problem with the requested skill's respons ...

Running the command npm show --outdated triggers an E404 error stating that the package is not found in this registry

I am currently working on a confidential project that I prefer not to make public. Despite using node v17.3.0 and npm 8.3.0, I am facing difficulties in displaying the outdated dependencies: $ npm show --outdated npm ERR! code E404 npm ERR! 404 Not Found - ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

Getting the json array value and populating it in a dropdown list in angularjs - a step-by-step guide!

{"id":1,"firstName":"John1","lastName":"Doe1","**accountIds**":[12345,12346,12347],"recipients":[{"accountNumber":22222,"firstName":"Mary1","lastName":"Jane1"},{"accountNumber":33333,"firstName":"Mary2","lastName":"Jane2"}]} Show the "accountIds" as a dro ...