An error has occurred due to a syntax issue with the unexpected

(For the full ASP.Net Core + Angular Universal code, visit this link)

Encountering an error when running my prerendered SPA using Angular Universal with "dotnet run" and navigating to any route. This issue does not occur when I execute it in the ClientApp folder with "npm run build:ssr && npm run start".

Request starting HTTP/1.1 GET https://localhost:5001/account/login  
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
    Microsoft.AspNetCore.NodeServices.HostingModels.NodeInvocationException: Prerendering failed because of error: /Workspace/ModuleIssue/ClientApp/node_modules/apollo-angular/ApolloModule.js:1
    (function (exports, require, module, __filename, __dirname) { import { NgModule } from '@angular/core';
                                                                         ^
SyntaxError: Unexpected token {
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
Current directory is: /Workspace/ModuleIssue

   at Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance.InvokeExportAsync[T](NodeInvocationInfo invocationInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance.InvokeExportAsync[T](CancellationToken cancellationToken, String moduleName, String exportNameOrNull, Object[] args)
   at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.InvokeExportWithPossibleRetryAsync[T](String moduleName, String exportedFunctionName, Object[] args, Boolean allowRetry, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.InvokeExportWithPossibleRetryAsync[T](String moduleName, String exportedFunctionName, Object[] args, Boolean allowRetry, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Builder.SpaPrerenderingExtensions.<>c__DisplayClass0_0.<<UseSpaPrerendering>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

This is the content of tsconfig.json:

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

Below is the information included in package.json:

{
  "name": "ModuleIssue",
  "version": "0.0.0",
  ...
}

The Node and NPM versions being used are as follows:

Node 10.8.0 
NPM 6.3.0

Answer №1

When creating an SSR bundle, node_modules modules are not transpiled, which means apollo-angular will not be transpiled either.

To resolve this issue, simply add a single line to your angular.json:

"server": {
      "builder": "@angular-devkit/build-angular:server",
      "options": {
        "outputPath": "dist/server",
        "main": "src/main.server.ts",
        "tsConfig": "src/tsconfig.server.json",
        "bundleDependencies": "all" // include this line
      },
...

then execute npm run build:ssr, and you will notice that the size of ClientApp/dist/server/main.js is quite large.

However, it appears there are some style-related problems 🤔

https://i.sstatic.net/T5rfh.jpg

Answer №2

After cloning your project, I made a simple adjustment by removing the

Microsoft.AspNetCore.SpaServices.Extensions
reference.

Surprisingly, this small change ended up resolving the issue completely!

Answer №3

Utilizing destructuring in your import statement like this:

import { NgModule } from '@angular/core'

Destructuring is a functionality outlined in ecma 6 (view specification). Consider adjusting the target to es6 in your tsconfig.json

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

A guide on harnessing the power of anchor tags and route parameters to retrieve JSON data based on a specific ID

As a newcomer to Angular, I've been putting in the effort to grasp the concepts. However, I've hit a roadblock when it comes to utilizing an anchor tag to navigate to a specific ID in a JSON file, and I'm unsure of how to proceed. <div n ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Optimal approach for transferring numerous variables with ajax

As a newcomer to jquery, I find myself inquiring about the most efficient approach for transmitting multiple variables to php through ajax. Should I bundle them up like this: $.ajax({ data:{ input: {x: 1, y: 2} }, ... }) or should I s ...

Looking to simplify the complex JSON structure by converting it into an array using JavaScript

Being a newcomer to javascript, I am struggling with breaking down a complex structure into an array. The current structure is as follows: [ { "Key": "ProducePRINKA0370001", "Record": { "docType": "Produce", "PR ...

Tips for delaying the execution of the next function until after a Firebase storage image upload is complete

I'm currently working on a function that involves uploading multiple images to Firebase, storing the returned URLs in an object, and then uploading that object to my Cloud Firestore database. However, my understanding of async/await and promises is li ...

Is there a method available to prevent text from being viewed in dev tools or through the click + inspect option?

I have come across a dilemma where I need to conceal certain text from users. Up until now, I have resorted to utilizing <body oncontextmenu="return false;"> along with a JavaScript function provided below: <script> document.onkeydown = fu ...

Managing the challenges of handling numerous AJAX post errors stemming from multiple form submissions

I am currently developing a PHP application that will be used to present multiple choice questions as well as text-based questions. The functionality I have implemented involves using Javascript code to submit user responses via ajax to the PHP server. He ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

How to incorporate a switch into an Angular Material filtered list?

My current task involves filtering a list that I am displaying multiple times using a toggle switch. The aim is to filter out the items that are disabled and switch them off, while displaying the regular list when the switch is on. I am utilizing Angular M ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

Integrating a custom extension within a design template

First and foremost, I am aware that what I'm about to do goes against recommended practices for several reasons. However, due to specific requirements that I won't delve into, this task is necessary. I have attempted to integrate a fairly simple ...

Discover the secrets to obtaining live website information using Google Script!

I am looking to retrieve the exchange rate data from a specific website. My understanding is that the website is dynamic (I'm still new to javascript) and the data is not easily accessible. Can anyone guide me on how to extract the exchange rates? For ...

Issue with clearing an array in JavaScript by reassigning it when accessed through a different reference variable

I discovered a workaround - by directly accessing the original array variable, I was able to achieve the desired result. Despite this, I am still intrigued by the reason behind this behavior. var array = ["hello"]; var testObject = {arr: array}; testObje ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

When an Angular2 application is deployed on a server running NginX, child components fail to load

After deploying my Angular2 app on a server as a Docker image and serving it with NginX, I encountered an unexpected issue. When I ran the webpack-dev-server locally to verify if the build was successful, everything looked fine https://i.sstatic.net/wQQ7 ...

Unable to perform queries from a separate file as connection.query function is not recognized

Currently diving into node.js and databases. Attempting a mysql query, but encountering the error TypeError: connection.query is not a function. Utilizing Node MySQL 2 (https://www.npmjs.com/package/mysql2) package; The connection and queries in app.js f ...

Automating email testing for Azure Graph-built applications: A step-by-step guide

I am exploring options to streamline the email testing process for an application developed with Azure Graph integration. Currently, I am leveraging playwright and typescript for other testing purposes within the application. One of the key functionaliti ...

Error: Unspecified object found in Three.js file

I am facing an issue where I have declared a global variable to store an OBJ loaded through THREE.OBJLoader, but when trying to animate the position or rotation of the object, I receive an error stating that the variable is undefined. Below is how I have ...

Rejecting the request by clicking a button

While switching to a menu, I retrieve data from the API. As the pending data is still loading in DevTools, I click on the Filter button to search for additional data. The data I am searching for appears in my table. However, once the pending data finishes ...