How to configure babel correctly to use lodash-es? - javascript

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

Adapted from https://stackoverflow.com/a/31822668/3563013
require("#babel/register")({
ignore: [/node_modules\/(?!lodash-es)/],
});

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

Related

Jest - Next.js - Unexpected token error inside jest node-modules

I installed jest with the following command on my next js project
npm i --save-dev jest #testing-library/react #testing-library/jest-dom jest-environment-jsdom
then added jest.config.json file with the below code
const nextJest = require("next/jest");
const createJestConfig = nextJest({
dir: "./",
});
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>/"],
testEnvironment: "jest-environment-jsdom",
};
module.exports = createJestConfig(customJestConfig);
Now, when I run 'npm test', I get the following error
Test suite failed to run
D:\my-project\node_modules\#jest\reporters\build\GitHubActionsReporter.js:67
#getMessageDetails(failureMessage, config) {
^
SyntaxError: Unexpected token '('
at Object. (node_modules/#jest/reporters/build/index.js:75:3)
I've tried a lot of solutions, updating the config file, adding babel plugins, none worked. And I haven't found any mention of this error online. What is the issue here?
My dev-dependencies versions -
"devDependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"eslint": "8.14.0",
"eslint-config-next": "12.1.5",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
As mentioned by jonrsharpe, the fix is to make sure you have an updated version of node installed.
This issue isn't limited to using Jest with a Next.js solution, but also applies to Jest being used with React/VanillaJs/etc

Gulp throws error 'Must use import to load ES Module'

We're converting our gulpfile.js in node v13.8.0 to ES6 as following:
import { src, dest, series, parallel, watch } from 'gulp'
import nodemon from 'gulp-nodemon' // normal nodemon does not display an error on app crash
import env from 'gulp-env'
import browser from 'browser-sync'
import sass from 'gulp-sass'
// Tasks
export default {
cssTranspile: cssTranspile,
jsTranspile: jsTranspile,
server: series(startNodemon, startBrowserSync),
default: series(
parallel(
cssTranspile,
jsTranspile
),
startNodemon,
startBrowserSync,
function () {
watch('public/scss/*.scss', cssTranspile)
}
)
}
The error reported, when simply running gulp, is:
internal/modules/cjs/loader.js:1160
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: T:\Node\ICP\gulpfile.js
require() of ES modules is not supported.
I must be doing something wrong. Anyone an idea on what it might be?
CLI version: 2.2.0
Local version: 4.0.2
The flag "type": "module", is set in package.json as described in the note docs. The issue is very much similar to this issue in the geolib library.
And when we rename gulpfile.js to gulpfile.babel.js as described here we get the same error.
The package.json contain these packages:
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/register": "^7.8.3",
"exports-loader": "^0.7.0",
"gulp": "^4.0.2",
"gulp-env": "^0.4.0",
"gulp-nodemon": "^2.4.2",
"gulp-sass": "^4.0.2",
"nodemon": "^2.0.2"
},
"type": "module",
"babel": {
"presets": [
"#babel/env"
]
In an answer to my own question, when the flag "type": "module" is set in package.json you can't use gulp. More info can be found here.
This seems to be fixed now: https://github.com/gulpjs/gulp-cli/pull/214. Be sure to install the latest version of gulp-cli (2.3.0 as of June 2020).
If your package.json specifies "type": "module" you can name your ES module with Gulp tasks gulpfile.js, otherwise name it gulpfile.mjs. No need to use any transpilers or preloaders like esm, Babel or TypeScript.

Trying ES6 style import gives 'Cannot use import statement outside a module'

I am trying to write a javascript test in intellij for which I need to import some dependancies and I want to use ES6 style import statements but getting error
/usr/local/bin/node /workspace/rr-sample/node_modules/mocha/bin/_mocha
--ui bdd --reporter "/Users/me/Library/Application Support/IntelliJIdea2019.1/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js"
tests/*.test.js /workspace/rr-sample/tests/App.test.js:3
import chai from 'chai'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1043:16)
at Module._compile (internal/modules/cjs/loader.js:1091:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14)
at Module.require (internal/modules/cjs/loader.js:1016:19)
at require (internal/modules/cjs/helpers.js:69:18)
at /workspace/rr-sample/node_modules/mocha/lib/mocha.js:334:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:331:14)
at Mocha.run (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:809:10)
at Object.exports.singleRun (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:108:16)
at exports.runMocha (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:142:13)
at Object.exports.handler (/workspace/rr-sample/node_modules/mocha/lib/cli/run.js:292:3)
at Object.runCommand (/workspace/rr-sample/node_modules/yargs/lib/command.js:242:26)
at Object.parseArgs [as _parseArgs] (/workspace/rr-sample/node_modules/yargs/yargs.js:1087:28)
at Object.parse (/workspace/rr-sample/node_modules/yargs/yargs.js:566:25)
at Object.exports.main (/workspace/rr-sample/node_modules/mocha/lib/cli/cli.js:68:6)
at Object.<anonymous> (/workspace/rr-sample/node_modules/mocha/bin/_mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:1121:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:67:12)
at internal/main/run_main_module.js:17:47
What exactly is the issue? I found this link (and others) http://xahlee.info/js/js_import_export.html which tells you how to fix this error but in another context which doesn't help me, and it doesn't explain what the problem is.
In case it is helpful here is the code I am using.
//const chai = require("chai");
import chai from 'chai'
const React = require("react");
const expect = chai.expect;
describe('how it works first-time test', () => {
it('checks equality', () => {
const val = false;
expect(val).to.be.false;
});
});
The easiest way to run Mocha tests written in ES6 is compiling them on-the-fly using Mocha --require #babel/register option (see https://github.com/mochajs/mocha/wiki/compilers-deprecation#what-should-i-use-instead-then). Of course, you need to make sure to install the corresponding modules and set up the .babelrc accordingly
package.json:
"dependencies": {
"#babel/cli": "^7.7.4",
"#babel/core": "^7.7.4",
"#babel/preset-env": "^7.7.4",
"#babel/register": "^7.7.4",
...
}
.babelrc:
{
"presets": [
[
"#babel/preset-env"
]
]
}
See also https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei
I had the same problem when updating one of my ts libraries to es6 modules instead of commonjs. After the change in the tsconfig.json my npm run test produced the mentioned error.
import chai from 'chai'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I solved it without babel by adding an own tsconfig file just for testing.
tsconfig.testing.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
},
"include": ["**/*.spec.ts"]
}
To run the tests via script in package.json
"test": "cross-env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha -r ts-node/register src/**/*.spec.ts",
(cross-env to set the env variable os independent)
I was able to get this working by adding a .mocharc.yaml file at the source of my project with the following:
require: '#babel/register'
source: https://github.com/mochajs/mocha-examples/tree/master/packages/babel
For me, I was not able to run it via inline debug option in intellj. So I set extra mocha option and this solved the issue.
--compilers js:babel-core/register
Also, to run via terminal
npx mocha --compilers js:babel-core/register
The cause of my issue was - an old version of Mocha, in fact any <6.0.0, even when the 'require: #babel/register' was configured. I updated Mocha to 9.0.0, I also updated Babel libraries to the latest and the problem was solved.
As it is also suggested in the Mocha docs, use config file, like '.mocharc.js', where you have to declare required Babel dependancy like in this example:
.mocharc.js
module.exports = {
...
require: '#babel/register',
...
}
package.json
{
...
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "7.18.6",
"#babel/register": "^7.9.0"
...
"mocha": "^9.0.0",
}
}
According to the doc:
https://nodejs.org/api/esm.html#esm_code_import_code_statements
So you have to ensure execute the script as an es module.
e.g. Execute the script using babel-node instead of Nodejs to enable the es6 or newer.

Js compress by uglify-js give error Unexpected token: name ($)

I am compress my js files by uglify-js
I want to compress Bootstrap 4 js file but it give me Error like this.
Can I compress all js files by only uglify-js Or how can i do it.
Parse error at src\bootstrap\alert.js:1,7
import $ from 'jquery'
^
ERROR: Unexpected token: name ($)
my package.json
"devDependencies": {
"node-sass": "^4.6.1",
"nodemon": "^1.12.1"
},
"dependencies": {
"autoprefixer": "^7.1.6",
"jquery": "^3.2.1",
"postcss-cli": "^4.1.1",
"uglify-js": "^3.1.9"
}
Try using the ES6 version of uglify-js. Replace with this in your package.json
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
or via command line:
npm install --save uglify-js#github:mishoo/UglifyJS2#harmony
uglify-js does not support ES2015 syntax like import statements or arrow functions. Instead, use the uglify-es module:
- "uglify-js": "^3.1.9"
+ "uglify-es": "^3.1.9"

Babel ES6 import error, SyntaxError: Unexpected token import

I am trying to set up a basic modular program, however I seem to be running into issues with importing modules. I attempt to import my custom module, I get the following error:
(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
^^^^^^
SyntaxError: Unexpected token import
The code that is causing the issue:
testcase.js
import testStep from 'testStep';
testStep.hello();
testStep.js
var testStep = {
hello: hello,
};
var hello = () => {
console.log('hello world');
};
export default {testStep};
package.json
{
"name": "rebuild-poc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0"
},
"dependencies": {}
}
.babelrc
{
"presets": [
"env"
]
}
I have already tried several other fixes, such as setting testStep as a class, as well as using require('./testStep.js'), however neither of those seem to have worked.
Do I have something set up incorrectly with babel or in one of my files?
***Edit: I am running testCase.js with node testCase.js.
Please install babel-cli and call your file with: ./node_modules/.bin/babel-node testcase.js
It will fail. Now we have to fix your code.
testStep.js should look like:
var hello = () => {
console.log('hello world');
};
var testStep = {
hello: hello,
};
export default testStep;
Then, it will work. ;)
This first introduction on https://babeljs.io/ is, that you should install babel-cli and babel-preset-env. ;)
You can also write your testStep.js like this:
var testStep = {
hello: hello,
};
function hello () {
console.log('hello world');
};
export default testStep;
This keeps the hoisting in mind. Like Jacob said in his first point.
From the babel 6 Release notes:
Plugin Presets
$ npm install --save-dev babel-preset-env
save it .babelrc file
{
presets: ["env"]
}
Note:
https://babeljs.io/docs/en/babel-preset-env#docsNav
You need to define hello with function, using var, you will not have function hoisting, so when declaring testStep, hello is undefined.
If you want to use es module, you can use babel-register or babel-node.
In your code, node can not handle es module.
Babel-register
With bebel-register, all your module will be handled by babel when they are imported.
First,yarn add babel-register babel-cli --dev or npm install babel-register
babel-cli -dev
Then create an entry file:
// entry.js
require('babel-register')
require('testcase')
In your testcase, you can use es module now.
Edit you package.json:
"scripts": {
"test": "node entry.js"
},
you can run yarn test or npm run test in terminal.
You don't need babel-polyfill, that is for browsers, not for node.

Categories

Resources