How to configure babel correctly to use lodash-es?

左心房为你撑大大i 提交于 2019-12-11 02:21:44

问题


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



回答2:


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

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


来源:https://stackoverflow.com/questions/52851818/how-to-configure-babel-correctly-to-use-lodash-es

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!