【问题标题】:How do I use babel in a node CLI program?如何在节点 CLI 程序中使用 babel?
【发布时间】:2015-10-05 11:32:00
【问题描述】:

我正在 node 中编写一个小型 CLI 工具,并希望为此使用 ES6。

index.js 看起来像:

#!/usr/bin/env node

require('babel/register');
module.exports = require('./app');

我可以很容易地调用它使用

$ node index.js --foo some --bar thing

在我的package.json 中声明以下内容:

  "bin": {
    "my-tool": "./index.js"
  }

在安装和执行此操作时,babel 似乎无法正常工作:

/usr/lib/node_modules/my-tool/app.es6:1
(function (exports, require, module, __filename, __dirname) { import yargs fro
                                                          ^^^^^^
SyntaxError: Unexpected reserved word

我在这里缺少什么?

【问题讨论】:

  • 不知道为什么会发生这种情况(我可以重现)。作为一种快速解决方法,也许您可​​以改用#!/usr/bin/env babel-node
  • 我认为 babel 的即时编译不适用于模块语法。
  • 那我根本不明白它的作用:通过node index.js(工作)和my-tool(不工作)调用时的区别在哪里?

标签: node.js command-line-interface ecmascript-6 babeljs


【解决方案1】:

require 钩子更多地用于本地开发而不是生产使用。理想情况下,您会在分发包之前进行预编译。你遇到了https://github.com/babel/babel/issues/1889

您需要明确告诉注册钩子不要忽略您的应用程序。

require('babel/register')({
  ignore: /node_modules\/(?!my-tool)/
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2019-07-18
    • 1970-01-01
    • 2017-08-16
    • 2016-07-02
    • 2016-06-13
    相关资源
    最近更新 更多