-->

“Unexpected token export” in Angular app with Syst

2020-07-18 05:08发布

问题:

Problem: mysterious "Unexpected token export"

I happened to get this error in an Angular example running in plunker where SystemJS transpiles TypeScript code in the browser.

There was nothing wrong with the code which ran fine locally.

回答1:

Solution

This isn't an Angular problem. It's a problem with transpiling certain kinds of TypeScript files in the browser.

In my case, I tracked the problem down to a single file that only exported an abstract class.

// Class used as a "narrowing" interface that exposes a minimal logger
// Other members of the actual implementation are invisible
export abstract class MinimalLogger {
  logs: string[];
  logInfo: (msg: string) => void;
}

The problem is that this file doesn't export anything other than the abstract class.

When I add an inert export of anything concrete ... like this:

export const _ = 0; // hack: must export something "real"

... the error goes away.

I've seen a similar problem with a file that only exports TypeScript interfaces. You have to give it at least one thing that is "real".

Environment:

  • typescript@2.2.1
  • systemjs@0.19.39

SystemJS Config for this example:

 System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    ...
  })