【问题标题】:gulpfile.ts fails with any import statementgulpfile.ts 因任何导入语句而失败
【发布时间】:2020-03-30 03:19:21
【问题描述】:

您预计会发生什么? 安装 ts-node 时给定 .ts 文件时的正常 gulp 操作

究竟发生了什么?

[10:24:59] Requiring external module ts-node/register
.\gulpfile.ts:3
import { __awaiter, __generator, __read, __spread } from "tslib";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
...

如果我 tsc 我的 gulpfile.ts,那么 gulp 可以完美地处理转译输出。只有当我直接给 gulp 它阻塞的 gulpfile.ts 时。如果我的文件包含任何导入语句,则标记我的第一条语句(即使它是注释)。

我使用import { src, dest, series, parallel } from 'gulp';(参见下面的示例)而不是const { src, dest, series, parallel } = require('gulp');,因为require() 是一个无类型的nodejs 函数(string) => any,丢失了所有的输入信息。我可以在我的 gulpfile 中出现各种类型错误而不会被检测到,这违背了在 TS 中编写它的目的。

使用下面的导入语句,VSCode 会立即检测到我的错误:

      src(srcFiles)
        .pipe<NodeJS.ReadWriteStream>(newer({dest: home, ext: '.js'}))
        .pipe<NodeJS.ReadWriteStream>(sourcemaps.init())
        .pipe<NodeJS.ReadWriteStream>(ts({
          lib: ['es2016', 'dom']
          , removeComments: true
        }))
        .pipe(uglify)
        .pipe<NodeJS.ReadWriteStream>(sourcemaps.write('.')) // sourcemap as separate file
        .pipe(dest(home))

但是没有打字,我花了一周的时间才注意到我哪里出错了。

实际上,如果我已将所有 require() 语句更改为正确键入的 import 语句,那么我不需要手动将类型提供给 pipe&lt;T&gt;() 以对其进行正确类型检查。

我已经为这些 tsconfig.json 选项尝试了许多不同的值组合:

  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "esnext",
    "moduleResolution": "node",
  }

ts-node 安装在本地。包.json:

  "devDependencies": {
    "ts-node": "8.8.1",
    "tslib": "^1.11.1",
    "typescript": "^3.8.3"
  }

唯一的出路是使用 gulp 将我的 gulpfile.ts 转换为 gulpfile.js 并启动第二个 gulp 来处理输出。但这听起来很复杂。

请发布您的 gulpfile 示例(最好减少到无法正常工作的部分) gulpfile.ts:

import { src, dest, series, parallel } from 'gulp';
import * as uglify from 'gulp-uglify';

你使用的是什么版本的 gulp?

CLI version: 2.2.0
Local version: 4.0.2

你使用的是什么版本的 npm 和 node?​​strong>

yarn -v
1.22.4

ts-node -v
ts-node v3.3.0
node v12.15.0
typescript v2.5.3

npm -v
6.7.0

【问题讨论】:

    标签: typescript import gulp


    【解决方案1】:

    我遇到了一个非常相似的错误:

    /project/gulpfile.ts:1
    import gulp from 'gulp'; // or import * as gulp from 'gulp'
           ^^^^
    
    SyntaxError: Unexpected identifier
    

    出现错误是因为 gulp 与 tsconfig.json 文件中 "esnext"module 值不兼容。在某些情况下,您可以只更改或删除此条目,但使用 create-react-app 时,它会在下次运行时覆盖您的编辑。

    您可以通过向您的tsconfig.json 文件添加ts-node 块来专门为ts-node 指定自定义编译器选项来解决此问题,例如:

    {
      "compilerOptions": {
        "module": "esnext"
      },
      "ts-node": {
        "compilerOptions": {
          "module": "commonjs"
        }
      }
    }
    

    通过此更改,您应该能够通过运行 gulp 来运行您的 gulpfile.ts

    【讨论】:

    • 我以为我已经尝试了所有模块值,但显然我没有。谢谢 :) 不幸的是,并非所有 glup 插件都有类型。
    猜你喜欢
    • 1970-01-01
    • 2013-01-15
    • 2015-02-09
    • 2017-06-14
    • 2016-03-17
    • 2015-06-22
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多