The seamless fusion of Express with Typescript

Hello and thank you for taking the time to assist me.

I recently completed a Cron app using Node.JS. I wanted to add a website hosted by the Node.js server with Express. I developed this TypeScript website in a separate folder, but encountered errors when trying to integrate it into my Node.js server. The errors are as follows:

shim.min.js       : 1 Uncaught SyntaxError: Unexpected token <
zone.js            : 1 Uncaught SyntaxError: Unexpected token <
Reflect.js         : 1 Uncaught SyntaxError: Unexpected token <
system.src.js      : 1 Uncaught SyntaxError: Unexpected token <
systemjs.config.js : 8 Uncaught SyntaxError: Unexpected token {
app                : 1 Uncaught SyntaxError: Unexpected token <
(index)            : 28 Uncaught SyntaxError: Unexpected token <
Evaluating http://localhost/public/app
Error loading http://localhost/public/app

Here is how my folders are organized:

project_tree

The issues seem to be related to my index.html and systemjs.config.js files. When I move node_modules to both the public and root directories, it works correctly. So, I believe the problem lies in the file paths.

<html>
  <head>
    <title>Cts</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">

    <link rel="icon" type="image/png" href="icone.png" id="icone" />

    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCCGhv7ryot0iu9ufz-BXlZBZxcYhB7q8c">
    </script>
     <script src="https://code.angularjs.org/tools/traceur-runtime.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <!--<script async defer src="http://maps.googleapis.com/maps/api/js?key=AIzaSyC6bfdXKHUFQltpGyCgC6cmVBx-gDWvxlM"></script>-->
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="../node_modules/core-js/client/shim.min.js"></script>
    <script src="../node_modules/zone.js/dist/zone.js"></script>
    <script src="../node_modules/reflect-metadata/Reflect.js"></script>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>



    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
     <base href="/" >

  </head>
  <!-- 3. Display the application -->
  <body>  
          <my-app>Loading...</my-app>
  </body>
</html>

Contents of systemjs.config.js:

(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', 
    '@angular':                   '../node_modules/@angular',
    'angular2-in-memory-web-api': '../node_modules/angular2-in-memory-web-api',
    'rxjs':                       '../node_modules/rxjs',
    'mapbox-gl':                  '../node_modules/mapbox-gl'

  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },

  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

I hope I have explained my issue clearly. Thank you in advance for your assistance.

Answer №1

It appears that the issue lies in your Express application not serving static files from the ../node_modules directory, but only from the public folder (which is the recommended approach). This could be causing the Unexpected token < errors, as Express defaults to sending the index.html file if the requested file cannot be served. Your observation that everything works when you move node_modules into the public folder supports this explanation.

One solution is to create a vendor folder within your public directory for serving client-side libraries. You can automate the process of copying necessary vendor files using a grunt task. Another option is to utilize CDN services to serve all client-side libraries. In your index.html, this might look like:

<script src="vendor/core-js/client/shim.min.js"></script>

or

<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/shim.min.js"></script>

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

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Stop openapi-generator from altering enum names in JavaScript/TypeScript

We have implemented the openapi generator to create our REST client and it has been quite effective. However, we encountered an issue when using enums in the format UPERCASE_UNDERSCORE, as it ended up removing the underscores which caused inconvenience. Th ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Leveraging Angular for Remote Configuration Management

How is everything going with you? I'm attempting to retrieve a configuration that I previously set up in Firebase's remote config using my Angular 15 application. The specific configuration is called "AllowedUsers." Here is the image of th ...

Generating an Express application with Socket.io in mind

After hours of searching, I am still unable to find an easy solution to my question. How can I start using Socket.io after generating the Express application? For instance, if I create a new app with express myapp and npm install --save socket.io, how do ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

Investigating TLS client connections with node.js for troubleshooting purposes

I am currently facing an issue while setting up a client connection to a server using node.js and TLS. My query revolves around how I can gather more information regarding the reason behind the connection failure. It would be great if there is a way to ob ...

Error in communication: Microsoft Bot framework encountered an issue with receiving a security token during the ChatConnector process

My Node.js bot framework version is 3.3.3 and I have successfully configured the "Skype" channel. However, when trying to set up the "Facebook Messenger" channel, I encounter an error stating "No security token sent". I am currently using ngrok for testing ...

Node.js asynchronous functions callbacks

Is there a way to capture the result value using the "SHA512crypto" callback function and apply it as the value in client.query? I've been struggling with getting only undefined value no matter what I do. Any help for a beginner in node.js? var SHA51 ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

Passport.js will direct you to a "302 Found" page following the authentication process

Passport.js allows users to specify success and failure redirection URLs after authentication: app.post('/login', passport.authenticate('local', { successRedirect: '/success.html', failureR ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

Obtaining JSON data created through the use of the stringify method

After retrieving data from a database, I stored it in an array. To convert this array into JSON format, I used the stringify method which resulted in the following JSON structure: var view_data = [{ f o o = " boo " , t e x t = "t e s t " }]; However, w ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Verify that a variety of records are present within a specific database

I am currently working with a database that contains around 40,000 documents structured like this: { "_id":{"$oid":"5e988b703117c034b0630f8"}, "name":"London Heathrow Airport", "country&qu ...

What is the process for accessing getBoundingClientRect within the Vue Composition API?

While I understand that in Vue we can access template refs to use getBoundingClientRect() with the options API like this: const rect = this.$refs.image.$el.getBoundingClientRect(); I am now attempting to achieve the same using template refs within the com ...

When the variable type is an interface, should generics be included in the implementation of the constructor?

Here is a code snippet for you to consider: //LINE 1 private result: Map<EventType<any>, number> = new HashMap<EventType<any>, number>(); //LINE 2 private result: Map<EventType<any>, number> = new HashMap(); When the ...

Deployment of the API and frontend on separate subdomains and domains respectively within the Google Cloud Platform

My journey began by setting up a Google App Engine where I deployed both the API and the frontend on my custom domain, which I referred to as mysite.ms. The API was written in nodejs with Express, while the frontend was a React application. To achieve this ...