Babel parser not showing proper filename for sytax error - node.js

So I've tried everywhere but can't find any answers to this. I am trying to add some custom functionality to a Gatsby build process that runs on node.js which requires me to get file content and parse into an ast. I am using #babel/parser successfully, however whenever the parser runs into syntax errors it throws an error referencing the file running the parser instead of the file being parsed (i.e. where the syntax error is actually located).
Here is an example from gatsby-node.js where I am trying to run the parsing function:
const contents = fs.readFileSync( file, 'utf-8' );
const ast = parser.parse( contents, {
errorRecovery: true,
plugins: [ 'jsx' ],
sourceFilename: 'SHOWME.js',
sourceType: 'module',
} );
Here is the actual syntax error in the file being parsed named Page.js:
import React from 'react';
import { useGroqQuery } = 'this should break';
And here is the error as displayed in terminal:
"gatsby-node.js" threw an error while running the createPages lifecycle:
Unexpected token (2:24)
119 |
120 | const contents = fs.readFileSync( file, 'utf-8' );
> 121 | const ast = parser.parse( contents, {
| ^
122 | errorRecovery: true,
123 | plugins: [ 'jsx' ],
124 | sourceFilename: 'SHOWME.js',
File: gatsby-node.js:121:20
SyntaxError: Unexpected token (2:24)
- index.js:742 Object._raise
[gatsby-groq]/[#babel]/parser/lib/index.js:742:17
- index.js:735 Object.raiseWithData
[gatsby-groq]/[#babel]/parser/lib/index.js:735:17
- index.js:729 Object.raise
[gatsby-groq]/[#babel]/parser/lib/index.js:729:17
As you can see, it's showing me neither the syntax error itself or the filename, only the line and column numbers. Pretty frustrating to debug. I have tried using the parser's errorRecovery and sourceFilename options but they aren't making a difference here.
Has anyone run into anything similar?

Related

How to use a dynamic import in a firebase cloud function using Javascript

How can I make this work without having the pre-deploy linter produce an error? If I disable the linter will it work on the cloud? (It works with my mocha tests).
async function() {
const { ChatGPTAPI } = await import('chatgpt');
}
29:32 error Parsing error: Unexpected token import
✖ 1 problem (1 error, 0 warnings)
Setting type: "module" in package.json produces error with the eslintrc.js

SyntaxError: Unexpected token ':' when run migration

I have an enviments.ts file.
class Environment {
get databaseName(): string {
return (
process.env.MODE === 'dev' ?
process.env.dataBaseDev :
process.env.dataBaseProd
);
}
}
export const Environments = new Environment();
and also migrate-mongo-config.js file in my root.
const Environments = require("./src/environment/environment.ts")
const config = {
mongodb: {
url: 'mongodbUrl',
databaseName: Environments.databaseName,
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
}
},
migrationsDir: "migrations",
migrationFileExtension: ".js"
};
module.exports = config;
when I run my migration I have this error ERROR. also added when I write the database name as static it works but when I want to manage it dynamically I have this error
Unexpected token ':' /Users/x/Desktop/v/x-backend/src/environment/environment.ts:2
get databaseName(): string {
^
SyntaxError: Unexpected token ':'
how can I solve this problem?
I believe the answer from Vahid Najafi is likely your problem candidate. Unfortunately his answer is very terse. For those starting to learn TypeScript, please allow me to elaborate on his answer.
When configuring your environment to use TypeScript you can enable a separation between TypeScript source code files and compiled output javascript code. The TypeScript compiler will read the source .ts files and output to .js files. It is generally recommended to keep these two collections of files in separate directories to allow building a deployment. To specify these different directories, you can modify your tsconfig.json file to specify the value for outDir and rootDir.
When you compile your .ts files using the command tsc the typescript files with type specific language will be converted to non-type-specific .js files. When considering your specific problem we see the file migrate-mongo-config.js refers to file ./src/environment/environment.ts. The file ./src/environment/environment.ts is a sourcecode file, not the compiled version. During runtime the program is expecting to refer to a javascript file, not a .ts file. So the corrective action is to modify the file migrate-mongo-config.js. Assuming you have configured your outDir to be ./dist the first line in the migrate-mongo-config.js should be altered.
Updated Version of migrate-mongo-config.js`
const Environments = require("./dist/environment/environment.js")
const config = {
mongodb: {
url: 'mongodbUrl',
databaseName: Environments.databaseName,
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
}
},
migrationsDir: "migrations",
migrationFileExtension: ".js"
};
module.exports = config;
Notice how the first line value ./src/... was changed to ./dist/...? Notice how the file extension was changed from .ts to .js? Vahid's example removes the extension altogether. I have not tried this so I am uncertain as to it's behavior.
If you find this fixes your issue, please award the points to Vahid Najafi as this is his original idea. I am merely filling in some of the beginner topics to round out the conversation.
You should require from dist (js):
const Environments = require("./dist/environment/environment")

How to fix Jest tests that are throwing "Cannot find module" error?

I’d appreciate some advice for an error I am running into while running Jest tests.
The code I am running can be found here as I am working on Mozilla’s Devtools:
https://hg.mozilla.org/mozilla-central/file
I have added an import statement to the file devtools/client/debugger/src/components/Editor/SearchBar.js. The file is here:

https://hg.mozilla.org/mozilla-central/file/tip/devtools/client/debugger/src/components/Editor/SearchBar.js
The import statement is:
import { PluralForm } from "devtools/shared/plural-form";
I use this function in my code change. For some reason this is creating errors in the tests "Editor.spec.js" and "SearchBar.spec.js".
Tests can be found here: https://hg.mozilla.org/mozilla-central/file/tip/devtools/client/debugger/src/components/Editor/tests
The error is: Cannot find module 'devtools/shared/plural-form' from 'SearchBar.js'
The function works perfectly fine when I run the code, but Jest is having a hard time resolving the module.
Any help would be appreciated!
I tried adding to modulePaths in the config file.
Cannot find module 'devtools/shared/plural-form' from 'SearchBar.js'
37 | import type SourceEditor from "../../utils/editor/source-editor";
38 |
> 39 | const { PluralForm } = require("devtools/shared/plural-form");
| ^
40 | // import { PluralForm } from "devtools/shared/plural-form";
41 |
42 | function getShortcuts() {
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (src/components/Editor/SearchBar.js:39:24)

Node, Webpack: You may need an appropriate loader to handle this file type

I am using webpack and trying to add one quill addon but I am getting error.
ERROR in ./core/functions/frontCore.js 39:26
Module parse failed: Unexpected token (39:26)
You may need an appropriate loader to handle this file type.
| * #param {File} file
| */
> function saveToServer(file: File) {
| const fd = new FormData();
| fd.append('image', file);
My webpack config is simple :
module.exports = {
// Entry point
entry: './core/functions/frontCore.js',
// Output
output: {
path: __dirname + '/public/dist',
filename: 'bundle.js'
},
mode: 'development'
};
Don't know why I am getting error. Firstly I was getting error in visual studio code with function saveToServer(file: File) that it need to be ts file but it was solved by an article here on SO. But I can't go through this don't know what is problem.

Unexpected token ILLEGAL - brunch generated app.js

I know this has been asked a million times, but I can't seem to locate the illegal characters in this line:
window.require.register("templates/application", Function('exports, require, module', "module.exports = Ember.TEMPLATES[module.id.replace('templates\\','')] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {\nthis.compilerInfo = [2,'>= 1.0.0-rc.3'];\nhelpers = helpers || Ember.Handlebars.helpers; data = data || {};\n var buffer = '', hashTypes, escapeExpression=this.escapeExpression;\n\n\n hashTypes = {};\n data.buffer.push(escapeExpression(helpers._triageMustache.call(depth0, \"outlet\", {hash:{},contexts:[depth0],types:[\"ID\"],hashTypes:hashTypes,data:data})));\n data.buffer.push(\"\\n\");\n return buffer;\n \n});\n//# sourceURL=templates/application.hbs"));
This line is from the app.js file generated using node/brunch from the simple empty branch of https://github.com/cbosco/ember-brunch.
I get the error:
Uncaught SyntaxError: Unexpected token ILLEGAL
in Chrome when pointing to localhost:3333. Firefox gives the following error:
SyntaxError: unterminated string literal
It looks like it's in the generated "templates" code in app.js. The same problem happens in the cbosco todomvc project.
Steps to recreate:
git clone git://github.com/cbosco/ember-brunch.git ember-skeleton -b empty
brunch new my_app -s ./ember-skeleton
cd my_app
brunch watch -s
point browser to localhost:3333

Resources