无法在 Node Typescript 应用程序中编写 ES6 语法

Unable to write ES6 syntax in Node Typescript app

我在导入模块时收到 exception

这是代码

import * as express from 'express';

export class Server {

    app: express.Application
    constructor() {
        const port = 3000 || process.env.PORT
        this.app = express()
        this.app.listen(port, () => {
            console.log(`Listening on Port: ${port}`)
        })
    }
}

export default new Server()

注: 我正在用 Angular 7 创建 API,客户端和服务器应用程序都有共同的 node_modules 和其他配置文件,例如 package.json and angular.json

同样的代码,我运行Angular 6运行正常。是否有任何配置问题?

更新 1:

Angular 6 项目,我用 Node v8.9.3 创建 和新的 Angular 7 项目 Node v10.14.2 并面临服务器代码是 运行 旧项目但在新项目中给出陈述错误的问题。

更新二:

当我把它改成

var express = require("express");

const app = express()
const port = 3001 || process.env.PORT
app.listen(port, () => {
    console.log(`Listening on Port: ${port}`)
})

module.exports = app;

它运行良好...但我需要使用 ES6 语法

我想我明白了:

Node 尚不允许 ECMAScriptModules(实验性)

所以不是这个:

import * as express from "express";

你应该使用这个:

var express = require("express");

但是你可以使用标志 --experimental-modules 使其编译(它还不稳定)。

可能是 tsconfig.json 中的问题。检查 compilerOptions.module。示例:

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