【问题标题】:SyntaxError: Unexpected token import - import * as gulp from 'gulp'SyntaxError: Unexpected token import - import * as gulp from 'gulp'
【发布时间】:2017-04-28 13:28:01
【问题描述】:

如果你运行 gulp,你会得到以下错误信息。

是否没有安装 gulpfile 所需的模块? ..

$ gulp
[22:17:15] Failed to load external module ts-node/register
[22:17:15] Failed to load external module typescript-node/register
[22:17:15] Failed to load external module typescript-register
[22:17:15] Failed to load external module typescript-require
C:\project\interview\gulpfile.ts:1
(function (exports, require, module, __filename, __dirname) { import * as gulp f                                 rom 'gulp';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Liftoff.handleArguments (C:\Users\admin\AppData\Roaming\npm\node_modules\gu                                 lp\bin\gulp.js:116:3)

【问题讨论】:

  • 对目标节点使用--module commonjs,包括通过ts-node运行时
  • 看起来你使用的是由 ts-node 动态编译的gulpfile.ts。这很好,但您需要通过 Typescript 或通过另一个中间编译器来定位 NodeJS 的模块系统(CommonJS 的衍生产品)才能使其工作。您正在使用 --module es2015 输出 gulpfile,可能是通过一个位于同一位置的 tsconfig.json 文件。

标签: node.js typescript gulp


【解决方案1】:

要让 gulp 与 ES6 导入一起工作,您需要做 3 件事:

  1. gulpfile.js 重命名为gulpfile.babel.js

  2. 运行这个命令:

npm i @babel/preset-env @babel/register -D
  1. .babelrc 文件添加到项目的根文件夹中,其中包含以下代码:
{
  "presets": [
    "@babel/preset-env"
  ]
}

您现在应该可以在 Gulp 文件中使用 ES6 导入了。

注意:如果您想在 Gulp 文件中使用 TypeScript,则应按照此处列出的步骤操作:

https://stackoverflow.com/a/49849088/1611058

【讨论】:

    【解决方案2】:

    1) 在您的 Projekt 文件夹中创建一个“.babelrc”文件(所有其他配置文件也在其中)

    • 代码(.babelrc)

      { "presets": ["es2015"] }

    2) 在你的 NPM 中设置/安装 Babel(参见 https://babeljs.io/setup)。例如。与节点:

    npm install babel-preset-env --save-dev

    【讨论】:

    • 您的回答存在一些问题。在第 2 步中,您说要安装 babel-preset-env,但在第 1 步中,您将 es2015 设置为预设,这与您告诉人们下载的预设不同。最后,您没有提到需要将.babel 添加到 gulp 文件中。
    猜你喜欢
    • 2021-04-24
    • 2017-03-06
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2016-10-04
    相关资源
    最近更新 更多