Typescript - 导入 Express 不起作用

问题描述 投票:0回答:5

我的应用程序中有这个,并安装了

@types/express
依赖项

import express = require('express');

当我运行服务器时,它指向

express
并说
this is an unexpected identifier
。我相信这是正确的 TS 语法,而
const express = ..
的常规 JS 方式也有同样的错误。

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

javascript typescript import require
5个回答
24
投票

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

    const express = require('express');

您可以将其转换为:

    import * as express from "express";

是的,您需要常规

express
作为依赖项和
@types/express
作为开发依赖项才能使 TypeScript 类型定义正常工作。


17
投票

您想要的语法将是

import express from "express";

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

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


0
投票

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

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

app.ts

import express, * as express_test from "express"

const app = express ? express() : express_test()

0
投票

这篇文章帮了我很多忙,主要是关于

module: "commonjs"
package.json 条目


0
投票

我遇到了这个问题,我所做的只是tsc fileName.ts然后我只使用了js版本

© www.soinside.com 2019 - 2024. All rights reserved.