Babel and Node - No stack trace on syntax errors - node.js

I am converting a project over from using gulp to using nodemon so that I can use ES6 with babel. I'm following a pretty simple procedure to do so, which is well described here. A quick look at my package.json:
{
"main": "index.js",
"scripts": {
"start": "FORCE_COLOR=3 nodemon --exec babel-node index.js"
},
"dependencies": {
"deps": "1.1.1"
},
"devDependencies": {
"#babel/cli": "^7.16.0",
"#babel/core": "^7.16.5",
"#babel/node": "^7.16.5",
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.16.5",
"nodemon": "^2.0.15"
},
"babel": {
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
}
When I run npm start, nodemon runs the app, and reruns on save, but it crashes with a syntax error:
[nodemon] starting `babel-node index.js`
[HPM] Proxy created: /auth -> http://localhost:8081/
/myproject/node_modules/#babel/core/lib/parser/index.js:93
throw err;
^
SyntaxError: Legacy octal literals are not allowed in strict mode. (38:46)
at Parser._raise (/myproject/node_modules/#babel/parser/src/parser/error.js:147:45)
at Parser.raiseWithData (/myproject/node_modules/#babel/parser/src/parser/error.js:142:17)
at Parser.raise (/myproject/node_modules/#babel/parser/src/parser/error.js:91:17)
at Parser.recordStrictModeErrors (/myproject/node_modules/#babel/parser/src/tokenizer/index.js:1444:12)
at Parser.readNumber (/myproject/node_modules/#babel/parser/src/tokenizer/index.js:1239:12)
at Parser.getTokenFromCode (/myproject/node_modules/#babel/parser/src/tokenizer/index.js:951:14)
at Parser.nextToken (/myproject/node_modules/#babel/parser/src/tokenizer/index.js:307:10)
at Parser.next (/myproject/node_modules/#babel/parser/src/tokenizer/index.js:169:10) {
loc: Position { line: 38, column: 46 },
pos: 933,
code: 'BABEL_PARSE_ERROR',
reasonCode: 'StrictOctalLiteral'
}
[nodemon] app crashed - waiting for file changes before starting...
There doesn't seem to be a stack trace to the place in my code where this error is happening. I managed to track it down with some careful understanding of the no octal error, but other errors that come up look very similar, with no stack trace to the place in my own code where the error occurs. How can I debug like that? Is there a way to configure babel to include the origin of the error from my code?

Running babel-node with Node 16.9 seems to fix this.
With Node 12 to 16.8:
SyntaxError: Legacy octal literals are not allowed in strict mode. (1:4)
at Parser._raise (/tmp/babel-test-3/node_modules/#babel/parser/lib/index.js:569:17)
With Node 16.9+:
SyntaxError: /tmp/babel-test-3/index2.js: Legacy octal literals are not allowed in strict mode. (1:4)
> 1 | a = 01;
| ^
2 |
at Parser._raise (/tmp/babel-test-3/node_modules/#babel/parser/lib/index.js:569:17)
No other changes were required.
A bug report has been filed.

It could potentially be that there is something wrong with the package itself. But babel is a properly and well maintained project so it could be something on your end
The error here is that leading zeros aren't allowed. Try and remove any instance of hard-coded leading zeros and then use +number or parseInt on any numbers which the values you won't know, such as from an API, reading from a database, or receiving user input.

Related

"Uncaught (in promise) ReferenceError: process is not defined" when migrating to Parcel 2

I'm trying to migrate a Node.js webapp from Parcel 1 to Parcel 2.
I have a function in the client-side javascript code (that Parcel bundles) that calls another function I'm importing from a utility functions file in the back-end Node.js code.
All other front-end functions work and all other Node.js functions which require Node.js process still work.
When I trigger calling this function in the code:
getCloudinaryUrl.js:22 Uncaught (in promise) ReferenceError: process is not defined
Everything worked just fine in Parcel 1, so I'm assuming this is a problem with my Parcel 2 configuration, not with Cloudinary.
The offending lines:
In getColudinaryUrl.js (back-end):
const { Cloudinary } = require('cloudinary-core');
...
// this is what triggers the error
const cloudName = process.env.CLOUDINARY_CLOUD_NAME;
const cl = new Cloudinary({
cloud_name: cloudName,
});
In index.js (front-end):
import getCloudinaryUrl from './../../utils/getCloudinaryUrl';
// then I'm calling it later on in the code
In server.js (back-end)
This is the only place in the code where I do dotenv.config:
const dotenv = require('dotenv');
...
dotenv.config({ path: './.env' });
My OLD package.json with Parcel 1 which worked:
...
"scripts": {
...
"watch:js": "parcel watch ./public/js/index.js --public-url /js --out-dir ./public/js --out-file bundle.js",
"build:js": "parcel build ./public/js/index.js --public-url /js --out-dir ./public/js --out-file bundle.js"
},
"devDependencies": {
...
"parcel-bundler": "1.12.3",
...
},
"engines": {
"node": "^14"
}
My NEW package.json file which doesn't work:
...
"scripts": {
...
"watch:js": "rm -rf .parcel-cache/ && parcel watch ./public/js/index.js --public-url /js --dist-dir ./public/js",
"build:js": "rm -rf .parcel-cache/ && parcel build ./public/js/index.js --public-url /js --dist-dir ./public/js"
},
"devDependencies": {
...
"parcel": "^2.0.0-nightly.524",
...
},
"engines": {
"node": "^14"
},
"default": "./public/js/bundle.js",
"targets": {
"main": false,
"default": {
"includeNodeModules": true,
"scopeHoist": false
}
}
I added rm -rf .parcel-cache/ && since otherwise a second build would always fail.
I read the migration guide and several other pages:
https://v2.parceljs.org/getting-started/migration/
https://v2.parceljs.org/features/module-resolution/
https://v2.parceljs.org/features/node-emulation/
It wasn't easy for me to read and, being rather new, Parcel 2 doesn't have many resources online to read over. That's how I ended up with the new package.json file above which gave me the least amount of errors (excluding the one above).
If there's anything else I should add to the question, I will gladly provide it.
How do I configure Parcel 2 to detect process in that one file?
It could be as easy as adding CLOUDINARY_CLOUD_NAME=something to a .env file in the project root?
A bit late, but for anyone ending up here, I eventually fixed it by removing the engines key from the package.json.

import ``,ESLint: Cannot read property 'range' of null Occurred while linting

The error is because of this line of code
item.component = () => import(`#/views/${_component}`)
If I modify .eslintrc.js, it works
'indent' : "off",
'template-curly-spacing' : "off",
But this way, eslint won't help me format the code
when I run the following code, He can't work, but eslint has no errors:
item.component = () => import(`#/views/` + _component)
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "10.0.1",
"eslint": "5.15.3",
node -v: v12.9.1
eslint -v: v6.8.0
vscode
Try setting your eslint indent rule to contain: ignoredNodes for template literals. My eslintrc.js has the following:
rules: {
indent: [2, "tab", {
ignoredNodes: ["TemplateLiteral"]
}],
... etc ...
}
That will ignore extended template literals.
If the above doesn't work, try deleting package-lock.json and node_modules then re-install with npm i or yarn. This will restore your packages and reset downline versions.

node throw error when use async/await syntax.but it works well with import/export syntax

nodemon throw the error when use async/await syntax:
**/node_modules/#babel/runtime/helpers/esm/asyncToGenerator.js:17
export default function _asyncToGenerator(fn) {
^^^^^^
SyntaxError: Unexpected token export
but it works well with import/export syntax.
package.json
{
"scripts": {
"dev": "nodemon --exec babel-node server/index.js",
}
"dependencies": {
"#babel/polyfill": "^7.2.5",
},
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/node": "^7.2.2",
"#babel/preset-env": "^7.2.3",
}
}
.babelrc
{
"presets": [
"#babel/preset-env"
]
}
asyncToGenerator.js
function asyncGeneratorStep(...) { ... }
export default function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
But I think it probably goes wrong because of my babel setting.
BTW, when I use typeof, it throws the same error
**/node_modules/#babel/runtime/helpers/esm/typeof.js:3
export default function _typeof(obj) {
^^^^^^
SyntaxError: Unexpected token export
update 6/12, 2020:
structure:
src (vue app)
server (express app)
|---- src
|---- babel.config.js
|---- index.js
package.json
babel.config.js
In this project, I have two babel config, one is for the vue's app, and another is for the express. What I want is running these apps at the project's root path.
And in the beginning, my script about running express is
nodemon --exec babel-node server/index.js
It can run express, but it gets the wrong babel config(project/babel.config.js)
And the solution is just to point out the specific path which babel confg you want to use(project/server/babel.config.js). So the correct script to run the express is
nodemon --exec babel-node --config-file ./server/babel.config.js server/index.js",
answering your comment:
nodemon doesn't know about babelrc (and it shouldn't). And babel (AFAIK) doesn't allow you to select the babelrc file that you want to use.
I think that you should merge your babelrc files and set the env flag when running babel-node. Like this: babeljs.io/docs/en/6.26.3/babelrc#env-option
Another option would be to make a script that renames the babelrc file each time the app is reloaded, or something like that (I don't understand why you need 2 .babelrc files)
In an answer no longer visible (probably deleted by a moderator) I read that there are more .babelrc files in the project.
From babel docs it seems that the .babelrc needs to be in the same directory of the subpackage. I suggest you to read that doc, probably you can find the solution that better fits your requirements.
Sorry for the vague answer, but due to the lack of details in your question (server/index.js file content, directories structure, etc.) I can't do better.

TypeError when mocking request with jest

I'm relatively new to node and am having issues trying to mock request using jest.
If my file to be tested has require('request'), and I try to run npm test, I get this error:
FAIL __tests__/sum-test.js (0.291s)
● sum › it adds 1 + 2 to equal 3
- TypeError: The super constructor to `inherits` must have a prototype.
at Object.exports.inherits (util.js:756:11)
at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/private-key.js:44:6)
at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/utils.js:16:18)
Here's my package.json, if that helps:
{
"name": "jesttest",
"version": "1.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest-cli": "^12.0.2"
},
"dependencies": {
"request": "^2.72.0"
}
}
Anyone know why this might be happening?
add jest.unmock('request') in your test file.
Jest will mock a fake require object when you require something in your file.In this situation, request is not the real request.So tell jext not mock request.

Arguments to path.resolve must be strings when running Grunt

My Grunt file:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
ts: {
dev: {
src: ["src/background/*.ts"],
out: ["build/background.js"],
}
}
});
grunt.loadNpmTasks("grunt-ts");
grunt.registerTask("default", ["ts:dev"]);
};
(I am using grunt-ts.)
System info
Windows 8.1
NodeJS v0.10.24
grunt-cli v0.1.11
grunt v0.4.2
I've already searched the Internet and found many resources about this error, but they all say that one should upgrade NodeJS and/or Grunt. I've already tried that. I had even completely re-installed Grunt, however, the error remained.
The complete error message:
P:\my-folder>grunt ts
Running "ts:dev" (ts) task
Warning: Arguments to path.resolve must be strings Use --force to continue
Aborted due to warnings.
package.json
{
"name": "regex-search",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-nodeunit": "~0.2.0",
"grunt-contrib-uglify": "~0.2.2",
"grunt-ts": "~1.5.1"
}
}
After comparing my Gruntfile with the officially provided sample file, I found my really silly mistake:
ts: {
dev: {
src: ["src/background/*.ts"],
out: ["build/background.js"],
}
}
out must not be an array!
The correct version:
ts: {
dev: {
src: ["src/background/*.ts"],
out: "build/background.js",
}
}
So in my particular case, a node module's main attribute in package.json was an array and not a string, example in history.js' package.json:
{
"main": [ './history.js', './history.adapter.ender.js' ]
}
The way I found this out was going to where the error originated in my node_modules and then did console.log(pkg.main) right above it.
Original stacktrace:
Fatal error: Arguments to path.resolve must be strings
TypeError: Arguments to path.resolve must be strings
at Object.posix.resolve (path.js:422:13)
at /Users/ebower/work/renvy/node_modules/browserify/node_modules/resolve/lib/async.js:153:38
at fs.js:336:14
at /Users/ebower/work/renvy/node_modules/grunt-browserify/node_modules/watchify/node_modules/chokidar/node_modules/readdirp/node_modules/graceful-fs/graceful-fs.js:104:5
at /Users/ebower/work/renvy/node_modules/grunt-mocha/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/graceful-fs.js:104:5
at FSReqWrap.oncomplete (fs.js:99:15)

Resources