Angular2 CLI express server.ts encountered an unexpected import token

Starting an Angular2 project and setting up the server with express and Angular CLI version 1.0.0-beta.25.5 has been challenging for me.

The file structure looks something like this:

project root
|-server
  |-server.ts
|-src
  |-app

When attempting to run nodemon server.ts, I encounter an error message that is puzzling:

https://i.sstatic.net/NdfL4.png

Despite imports working in other parts of my application, the issue with this import statement remains unresolved. There are no indication of any incorrect imports in VS Code errors either. Both express and body-parser have been installed using npm install --save, along with @types/express (--save-dev). What could be causing this import statement to not work, and how can it be fixed?

server.ts

import * as express from 'express';
import {Application} from 'express';
import {apiFoods} from './api/apiFoods';

const bodyParser = require('body-parser');
const app: Application = express();
app.use(bodyParser.json());

apiFoods(app);

app.listen(8090, () => {
    console.log('Server is now running on port 8090 ...');
}); 

Answer №1

If you're looking to enjoy native es6 support, consider upgrading your node version to 7.x. Alternatively, you can utilize babel-node in conjunction with nodemon by executing the following command:

nodemon -w --exec "babel-node server.ts"

To specify specific folders for monitoring changes, simply append a folder name after the -w flag like -w server

For babel-node to function properly, remember to install the babel-preset-es2015 package by running:

npm install --save-dev babel-preset-es2015

Lastly, create a .babelrc file next to your package.json file containing the following configuration:

{
  "presets": ["es2015"]
}

Answer №2

The issue at hand lies in the use of the import statement, which is specific to ES6 and not compatible with Node.js. One approach that proved effective for me was incorporating ts-node to transpile my typescript code before executing it.

npm install --save-dev ts-node

Then, include a new script entry in your package.json file:

package.json

"scripts": {
  "api-server": "./node_modules/.bin/ts-node ./server/server.ts"
}

To run this script, use the following command:

npm run api-server

If you wish to utilize nodemon for watching changes, follow this method (adapted from this source):

nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec './node_modules/.bin/ts-node' server/server.ts

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

Error encountered when attempting to inject a service into another service due to circular dependency issues

I have encountered an issue while working on my Angular 5 application where I am facing errors when trying to inject one service into another service. Below is a snippet of the DataService: import { Injectable } from '@angular/core'; import { H ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Encountering a TypeScript React issue with passing objects to context in code

Within my project, there is a context provider that acts as an object containing various properties: <Provider value={ { scaleNum: scaleNum, // number scaleLet: scaleLet, // string ...

Utilizing Angular Material for Styling the Web

https://i.sstatic.net/GVcgu.png I am new to working with Angular and currently, I have a sidenav container with the content being a mat toolbar. My issue is that when viewed on a full-sized desktop, the background color of the toolbar stretches and fills t ...

Incorporating a d3 chart into an Angular 4 project

Currently, I am in the process of developing an Angular application using TypeScript. My aim is to incorporate a force directed network graph from Mike Boston built with d3, which can be viewed here. After successfully translating most of the code to Type ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

Having trouble launching React application on local machine due to missing node modules

I am completely new to React. I recently forked a project on Github and am attempting to run it on my own machine. However, I've noticed that the folder structure is missing the node modules. Does this mean I need to install create-react-app globally ...

Best Practices in D3 Visualization Using Static Data Architecture

My current project involves a D3 data visualization that creates a force layout graph using data from a JSON file containing 500 objects. The application is developed using node and express. I'm contemplating whether it's advisable to store this ...

How can eslint be used to enforce a particular named export?

Is there a way to use eslint to make it mandatory for JavaScript/TypeScript files to have a named export of a specific name? For instance, in the src/pages folder, I want all files to necessitate an export named config: Example of incorrect usage src/page ...

Assign a value to a variable within an asynchronous function

Initially, I understand that initializing variables inside asynchronous functions is not a feasible approach. However, I require assistance in rectifying this issue. In the following example, I have an observable and aim to extract its variable for use i ...

When trying to open the phonegap-plugin-barcodescanner on Android Studio with Ionic 6 and Capacitor, I encounter an error

Encountered an issue while trying to build the app in Android Studio. The error message "Could not find method compile() for arguments [{name=barcodescanner-release-2.1.5, ext=aar}] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.Defau ...

Is there a way to effectively eliminate an array of objects in JavaScript or TypeScript and alter the object structure simultaneously?

I am seeking solutions to restructure an object that has multiple arrays of objects so that I can access the object directly. console.log(value.data.summary[0].data) Instead of accessing arrays in this manner, I want to modify my data structure. Is there ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...

Issue Occurs when Updating Data in Node.js with MongoDB: Patch Method Returns Success but No Changes Reflect in Database

Recently, I've been attempting to make changes to my "Orders" by updating the product, quantity, and _id fields. However, even after running the patch command, it seems like nothing actually gets updated. Check out my API Update code screenshot here. ...

What is the best approach to creating multiple dropdowns in ant-design with unique options for each?

It seems like I may be overlooking a simple solution here. Ant-Design dropdowns utilize an array of ItemProp objects to show the options, but this restricts me to having only one list of options. const choices: MenuProps['items'] = [ { label: ...

Tips for managing onChange events in TypeScript

I'm still learning Typescript and I have a question regarding handling the onChange event in a TextField component when using Typescript. Can you provide guidance on how to approach this? I currently have a function called handleChangeDate(e: React. ...

A guide to mastering Nested Table creation in Angular

I'm in the process of creating a dynamic table using an array of data let data = [{ "criterialimitId": "3", "criteriaName": "Test", "criteriaId": "1", "criteria": "Max Wager", "type": "DAILY", "oprLimit": "2.5", "status": "1", "acti ...

Synchronously updating the state in Angular using NgRx

Currently, I have implemented NgRx-Effects along with an action to fetch data from a service and update my initial state. The state property name, let's call it 'schoolData', is functioning smoothly. However, I now require to modify the sam ...

Incorporate a double column to a Sequelize database using the Postgres dialect

I am in the process of establishing a relationship between the parents table and the children table, and this is my approach: // 20210226075430-create-child.js (children migration file) module.exports = { up: async (queryInterface, Sequelize) => { ...