首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeScript:只能使用“esModuleInterop”标志默认导入

TypeScript:只能使用“esModuleInterop”标志默认导入
EN

Stack Overflow用户
提问于 2022-03-28 07:21:02
回答 1查看 2.2K关注 0票数 2

我有下面的index.ts

代码语言:javascript
复制
import { User } from "./datatypes"
import express from 'express';

 console.log("hello world")

这是我的package.json

代码语言:javascript
复制
{
  "name": "simple_app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "tsc index.ts && node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.0",
    "express": "^4.17.3"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.23",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  }
}

这是我的tsconfig.json:

代码语言:javascript
复制
{
    "compilerOptions": {
      "module": "commonjs",
      "esModuleInterop": true,
      "resolveJsonModule": true,
      "target": "es6",
      "moduleResolution": "node",
      "sourceMap": true,
      "outDir": "dist"
    },
    "lib": ["es2015"]
  }

当我编写npm run start时,我获得:

代码语言:javascript
复制
 Module '"/mnt/c/Users/raffa/Desktop/simple_app/node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag

2 import express from 'express';
         ~~~~~~~

  node_modules/@types/express/index.d.ts:133:1
    133 export = e;
        ~~~~~~~~~~~
    This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

我该如何解决这个问题?

EN

Stack Overflow用户

回答已采纳

发布于 2022-03-28 14:07:32

如果您使用特定的文件路径从命令行调用tsc,它将忽略您的tsconfig.json

打字本文档(https://www.typescriptlang.org/docs/handbook/tsconfig-json.html):

当在命令行上指定输入文件时,将忽略tsconfig.json文件。

这意味着,如果调用esModuleInterop,则tsconfig.json的tsc index.ts部分将没有任何效果。

可以通过使用import * as express from 'express';来解决这个问题,但是可能还有其他一些问题是由于忽略TS吐露而引起的。

tsc -w && node index.js的一个问题(来自其中一个注释)是,-w会让它等待而不是自行终止,这意味着您不会在"&&“之后到达该部分。

因此,您将不会进入node index.js部分。

(但至少这次,tsc没有得到一个特定的文件,因此配置不会被忽略)

另外,在您的配置中,outDir被设置为dist,所以编译的文件将放在那里。因此,您应该使用以下方法:

tsc && node ./dist/index.js

票数 7
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71643703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档