【问题标题】:Using lodash module in babel-node REPL?在 babel-node REPL 中使用 lodash 模块?
【发布时间】:2017-05-10 11:48:42
【问题描述】:

我正在尝试测试 lodash,显然以下行在 REPL 中不起作用:

import curry from 'lodash/curry';

参见,例如,babel-node es6 "Modules aren't supported in the REPL" Why does babel-node not support module loading in the REPL?

有没有办法可以将像 lodash 这样的模块预加载到 babel-node 中? (例如,通过命令行选项或配置文件)

如果没有,是否有另一种方法可以在预加载 lodash 的情况下评估 ES6?

到目前为止,我已经在https://babeljs.io/repl/ 尝试了在线 REPL,并在 Firefox 的控制台中进行了评估。没有工作。

【问题讨论】:

    标签: ecmascript-6 babeljs lodash


    【解决方案1】:

    import肯定不行,因为要先安装包,然后打包才能导入,这不是Babel REPL的职责。

    Lodash 已经在 Babel REPL 中加载和使用,it can be used in REPL as _ global:

    const { curry } = _;
    

    如果问题不限于 Lodash,在 REPL 中获取第三方库的最快方法是手动加载脚本。由于 Babel 网站已经加载了 jQuery(就像几乎所有网站一样),所以在控制台中执行此操作的最短方法是 jQuery.getScript

    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js');
    

    之后 Lodash _ global 在 REPL 中可用。

    整个代码可以用回调包裹以跳过控制台部分:

    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js', () => {
      console.log(_.VERSION);
    });
    

    babel-node REPL 不支持导入,正如原始帖子中的链接所说。相反,应该使用 require,就像 Node 中的其他任何地方一样。

    var { curry } = require('lodash')
    

    这需要将lodash 安装在当前工作目录中存在的node_modules 中。

    【讨论】:

    • 感谢您的回答。我正在使用babel-node --presets es2015,在执行> const { curry } = _; 时,我得到了TypeError: Cannot read property 'curry' of undefined at repl:4:17 ... 有什么建议吗?
    • 答案首先针对 Babel REPL。当然,在 babel-node 中没有 _ global。你应该只是 require,就像通常在 Node 中一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    相关资源
    最近更新 更多