How to configure babel correctly to use lodash-es?
Asked Answered
P

2

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

Plonk answered 17/10, 2018 at 9:43 Comment(2)
Probably relevant: github.com/babel/babel/issues/7566Learnt
@Learnt Thanks I just tried the solution in the list, adding --ignore something, but it doesn't work: github.com/babel/babel/issues/7566#issuecomment-404927017Plonk
O
2

Adapted from https://mcmap.net/q/218667/-import-a-module-from-node_modules-with-babel-but-failed

require("@babel/register")({
    ignore: [/node_modules\/(?!lodash-es)/],
});
Outwardbound answered 28/8, 2019 at 8:45 Comment(1)
The ignore line should be in your babel.config.js file (or .babelrc).Vulcan
C
-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'));
Community answered 17/10, 2018 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.