【问题标题】:Unable to write ES6 syntax in Node Typescript app无法在 Node Typescript 应用程序中编写 ES6 语法
【发布时间】:2018-12-19 05:42:03
【问题描述】:

我在导入模块时收到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 创建的 以及带有Node v10.14.2 的新Angular 7 项目,并面临服务器代码与旧项目一起运行但在新项目中出现规定错误的问题。

更新 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 语法

【问题讨论】:

  • 这是服务器的全部代码吗?
  • 是的,就是完整的代码
  • 我看不出这部分代码有什么问题。您确定这部分导致编译失败吗?
  • 此代码在Angular 6 下运行良好,但在Angular 7 下运行良好。是否有任何兼容性或语法问题
  • 这段代码与Angular无关,就是Node。您是否更改了节点版本?

标签: node.js express import mean-stack


【解决方案1】:

这可能是 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"
    ]
  }
}

【讨论】:

  • 这与 Angular 无关。这是一个与 Angular 一起使用的快速 js 应用程序。
  • @Vinit Sarvade 我不在这里写关于 Angular 的文章)。我在服务器端使用打字稿,有时问题出在错误的配置中。请更详细地向我解释您的评论...
  • 这不是配置错误的问题。您还需要为您的 express 应用程序安装类型。请安装以下npm i -D @types/express,然后修改导入为import express from 'express'
  • 还要确保您正在使用tsc 命令运行应用程序。假设您的服务器代码在 server.ts 中,请使用 tsc server.ts 运行它
  • @Vinit Sarvade 如果 target 不是 es5 您将收到此错误。因为在输出中将是 import 并且 nodejs 在没有标志 --experimental-modules 的情况下无法理解它。
【解决方案2】:

我想我明白了:

节点还不允许 ECMAScriptModules(实验性)

所以不要这样:

import * as express from "express";

你应该使用这个:

var express = require("express");

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

this Question

【讨论】:

  • 使用相同的命令来运行这两个应用程序。这是专业人士使用的标准命令
  • 那么为什么这个 ES6 语法支持以前的项目,而它安装了以前的包而不是新项目安装了最新的包
  • 也许它是用 babel 编译的? (这是可能的)或者这个命令
  • 如何查看正在编译的内容?
  • 用于启动服务器的命令决定了它的编译方式。(babel /src 或 node /src)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 2017-07-24
相关资源
最近更新 更多