【问题标题】:`import XXX from` returns undefined while `const XXX = require` works in ts-node + Gulp`import XXX from` 返回 undefined 而 `const XXX = require` 在 ts-node + Gulp 中工作
【发布时间】:2021-12-30 07:09:48
【问题描述】:

作品(文件为gulpfile.ts):

const Gulp = require("gulp");

不起作用(没有 TypeScript 错误,但 Gulp 是 undefined):

import Gulp from "gulp";

tsconfig.json:

{
  "compilerOptions": {

    "target": "ES2020",
    "module": "CommonJS",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,

    "strict": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,

    "allowJs": false,
    "skipLibCheck": true,

    "baseUrl": "./",
    "paths": {}
  }
}

命令:

gulp <Any declared Gulp task>

【问题讨论】:

  • gulpfile.ts 长什么样?不正确的导出逻辑可能导致意外行为
  • @Leemellaret,感谢您的评论。只需import Gulp from "gulp"; console.log(Gulp); 就足以实现最小的复制。当然,Gulp 会告诉Task never defined: Deploy,但在此之前会输出undefined。如果将第一行替换为var Gulp = require("gulp");,undefined 将消失。

标签: typescript gulp ts-node


【解决方案1】:

通过编写import Gulp from "gulp",您正在尝试导入似乎不存在的gulp 的default 导出。

TypeScript 中 const Gulp = require("gulp"); 的实际等价物是“将所有导出导入单个变量”语法:

import * as Gulp from 'gulp';

如果您需要import Gulp from "gulp" 语法,您可以使用esModuleInterop TypeScript option 自动添加default 导入

有关 CommonJS 互操作性和 esModuleInterop TypeScript option 的更多信息,请参见我的其他答案:Why does typescript allow me to import dependencies it can't use at runtime?

【讨论】:

  • 感谢您的回答!您的解决方案有效,但我知道import Gulp from "gulp"; 在某些条件下也可以正常工作。 “我知道”意味着我有一些与import Gulp from "gulp"; 合作的项目。但这是什么条件?
  • 找到了这个条件!它丢失了"esModuleInterop": true。我可以请你在你的好答案中添加这个吗?
  • 是的,我今天晚些时候会做(现在在我的手机上)
  • 一旦你更新它,我会接受你的回答。再次感谢!
  • 我已经编辑了我的答案,提前感谢您的接受!
猜你喜欢
  • 2019-06-14
  • 1970-01-01
  • 2021-11-08
  • 2012-01-15
  • 2021-04-20
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
相关资源
最近更新 更多