How to configure babel correctly to use lodash-es?

2019-07-31 06:07发布

问题:

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

回答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'));