【问题标题】:How to configure babel correctly to use lodash-es?如何正确配置 babel 以使用 lodash-es?
【发布时间】:2018-10-17 09:43:28
【问题描述】:

我需要在我的项目中使用lodash-es,但是我无法正确配置我的babel,它总是报SyntaxError: Unexpected identifier之类的错误

hello.js

import upperCase from 'lodash-es/upperCase'

console.log(upperCase('lodash-es'));

package.json

{
  "scripts": {
    "demo": "babel-node hello"
  },
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.0.0",
    "@babel/node": "^7.0.0",
    "@babel/preset-env": "^7.0.0"
  },
  "dependencies": {
    "lodash-es": "4.17.11"
  }
}

.babelrc

{
  "presets": [
    "@babel/preset-env"
  ]
}

运行babel-node hello时,报错如下:

> /javascript-babel-node-use-lodash-es-issue-demo
> babel-node hello

/Users/freewind/workspace/javascript-babel-node-use-lodash-es-issue-demo/node_modules/lodash-es/upperCase.js:1
(function (exports, require, module, __filename, __dirname) { import createCompounder from './_createCompounder.js';
                                                                     ^^^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)

我也为此问题设置了一个小演示,如果需要,您可以克隆并尝试:https://github.com/freewind-demos/javascript-babel-node-use-lodash-es-issue-demo

【问题讨论】:

标签: javascript babeljs babel-node lodash


【解决方案1】:

改编自https://stackoverflow.com/a/31822668/3563013

require("@babel/register")({
    ignore: [/node_modules\/(?!lodash-es)/],
});

【讨论】:

  • ignore 行应该在您的babel.config.js 文件(或.babelrc)中。
【解决方案2】:

babel-node 默认忽略node_modules 目录。这是一件好事,否则它会不必要地沉重。 node_modules 中的包(目前)预计为 commonjs 格式。而不是使用lodash-es(es6 格式),你应该只使用lodash(commonjs 格式)。它具有完全相同的功能,唯一的区别是它的编写格式。有关here的更多信息。

因此,要么将 babel-node 调整为取消忽略 node-modules/lodash-es(不推荐!),要么将 lodashnpm install --save lodash 一起安装,然后像这样重写您的导入:

import upperCase from 'lodash/upperCase' // instead of lodash-es

console.log(upperCase('lodash-es'));

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2019-10-27
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多