【问题标题】:Typescript - Importing Express not workingTypescript - 导入 Express 不起作用
【发布时间】:2019-11-14 17:53:14
【问题描述】:

我在我的应用程序中安装了 @types/express 依赖项

import express = require('express');

当我运行我的服务器时,它指向express 并说this is an unexpected identifier。我相信这是正确的 TS 语法,const express = .. 的常规 JS 方式也有同样的错误。

我需要普通快递吗?或者我不需要我已经安装的那个应该专门用于 TS 的?

【问题讨论】:

    标签: javascript typescript import require


    【解决方案1】:

    你想要的语法是

    import express from "express";
    

    并且它不应该导致重复标识符错误,除非它只是一个 IDE 错误。您可以在此处查看大多数人用于使用 NodeJS/Typescript 的常见设置。

    https://github.com/microsoft/TypeScript-Node-Starter

    【讨论】:

    • 欣赏答案,运行 server.ts 时仍然给我同样的错误
    • 嗯,请确保您使用“tsc”构建应用程序并确保您的文件扩展名是“.ts”
    • 明白了,是的,我有一个由tsc --init 生成的tsconfig.json 文件,还有一个包含该导入语句的server.ts 文件
    • 嗯......很难确定它是什么......它说常规JS方式也是一个错误的事实让我怀疑它就像文件中某处的无效字符上面的导入或“这是一个意外的标识符”
    【解决方案2】:

    require语句替换为import语句,例如:

        const express = require('express');
    

    您可以将其转换为:

        import * as express from "express";
    

    是的,您需要两者,常规的 express 作为依赖项和 @types/express 作为开发依赖项才能使 TypeScript 类型定义正常工作。

    【讨论】:

      【解决方案3】:

      我遇到了一个特别困难的情况,因为我在生产/开发中使用 esmodules,而在测试工具中使用 commonjs。

      我最终通过使用两个导入来让它工作。

      app.ts

      import express, * as express_test from "express"
      
      const app = express ? express() : express_test()
      

      【讨论】:

        猜你喜欢
        • 2017-03-11
        • 1970-01-01
        • 2018-08-06
        • 2022-11-10
        • 2021-04-15
        • 2020-04-14
        • 2017-04-10
        • 2017-09-04
        • 2018-01-06
        相关资源
        最近更新 更多