4

I need to use lodash-es in my project, but I can't configure my babel correctly, it always reports errors like 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"
  ]
}

When run babel-node hello, it reports error like:

> /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)

I've also setup a small demo for this issue, you can clone and try it if you need: https://github.com/freewind-demos/javascript-babel-node-use-lodash-es-issue-demo

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • Probably relevant: https://github.com/babel/babel/issues/7566 – zerkms Oct 17 '18 at 09:48
  • @zerkms Thanks I just tried the solution in the list, adding `--ignore something`, but it doesn't work: https://github.com/babel/babel/issues/7566#issuecomment-404927017 – Freewind Oct 17 '18 at 09:56

2 Answers2

2

Adapted from https://stackoverflow.com/a/31822668/3563013

require("@babel/register")({
    ignore: [/node_modules\/(?!lodash-es)/],
});
McKabue
  • 2,076
  • 1
  • 19
  • 34
-1

babel-node by default ignores the node_modules directory. Which is a good thing, else it would be unnecessarily heavy. Packages in node_modules are (at the moment) expected to be in commonjs format. Instead of using lodash-es (es6 format) you should just use lodash (commonjs format). It has exactly the same functionality, the only difference is the format it is written in. More information about that here.

So either tweak babel-node to unignore node-modules/lodash-es (not recommended!) or just install lodash with npm install --save lodash and then rewrite your import like:

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

console.log(upperCase('lodash-es'));
axm__
  • 2,463
  • 1
  • 18
  • 34