Uncaught SyntaxError: Unexpected token export - javascript

I have used create-react-app for my project. I am getting an error of
Uncaught SyntaxError: Unexpected token export
The error is in this code
export const ENGLISH = {
lang: 'en',
messages: {
'nav.translatedMessage': 'Social',
}
};
I tried installing babel-preset-es2015 and babel-preset-stage-0. Also i included the babel dict/object in package.json as
"babel": {
"presets": [
"es2015",
"stage-0"
]
},
I am still getting an error.

I got my answer on README.md of create-react-app. There it says
You may create subdirectories inside src. For faster rebuilds, only
files inside src are processed by Webpack. You need to put any
JS and CSS files inside src, or Webpack won’t see them.

I think its because of the comma
export const ENGLISH = {
lang: 'en',
messages: {
'nav.translatedMessage': 'Social'
}
};
Try doing this !

Related

SyntaxError: Invalid or unexpected token when run nestjs

When I run this nestjs code, I encounter an error:
SyntaxError: Invalid or unexpected token
what is the reason?
import {Controller, Get, Bind, Req, Post} from '#nestjs/common';
#Controller('cats')
export class catsController {
#Post()
create() {
return "this is a action 1ss"
}
#Get()
#Bind(Req())
findAll(request) {
return "this is a action";
}
}
If you are just using JavaScript, not Typescript, you need to have a babel config like the following
// .babelrc
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
And then use babel-node instead of node so that babel can properly interpret the decorators.
The docs even mention this on the getting started page
Nest takes advantage of the latest language features, so to use it with vanilla JavaScript we need a Babel compiler.

Module parse failed: Unexpected token ? Optional chaining not recognised in threejs svgloader.js [duplicate]

Project setup:
Vuejs 3
Webpack 4
Babel
TS
We created the project using vue-cli and add the dependency to the library.
We then imported a project (Vue Currency Input v2.0.0) that uses optional chaining. But we get the following error while executing the serve script:
error in ./node_modules/vue-currency-input/dist/index.esm.js
Module parse failed: Unexpected token (265:36)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| getMinValue() {
| let min = this.toFloat(-Number.MAX_SAFE_INTEGER);
> if (this.options.valueRange?.min !== undefined) {
| min = Math.max(this.options.valueRange?.min, this.toFloat(-Number.MAX_SAFE_INTEGER));
| }
I read that Webpack 4 doesn't support optional chaining by default. So, we added the Babel plugin for optional chaining. This is our babel.config.js file:
module.exports = {
presets: ["#vue/cli-plugin-babel/preset"],
plugins: ["#babel/plugin-proposal-optional-chaining"],
};
(But, if I am correct, this plugin is now enable by default in the babel-preset. So this modification might be useless ^^)
One thing that I don't understand is that we can use optional chaining in the .vue files.
I created a SandBox with all the files: SandBox
How could I solve this error?
I was able to overcome this issue using #babel/plugin-proposal-optional-chaining, but for me the only way I could get Webpack to use the Babel plugin was to shove the babel-loader configuration through the Webpack options in vue.config.js. Here is a minimal vue.config.js:
const path = require('path');
module.exports = {
chainWebpack: config => {
config.module
.rule('supportChaining')
.test(/\.js$/)
.include
.add(path.resolve('node_modules/PROBLEM_MODULE'))
.end()
.use('babel-loader')
.loader('babel-loader')
.tap(options => ({ ...options,
plugins : ['#babel/plugin-proposal-optional-chaining']
}))
.end()
}
};
NB replace "PROBLEM_MODULE" in the above with the module where you have the problem.
Surprisingly I did not need to install #babel/plugin-proposal-optional-chaining with NPM. I did a go/no-go test with an app scaffolded with #vue/cli 4.5.13, in my case without typescript. I imported the NPM module that has been causing my grief (#vime/vue-next 5.0.31 BTW), ran the serve script and got the Unexpected token error on a line containing optional chaining. I then plunked the above vue.config.js into the project root and ran the serve script again, this time with no errors.
My point is it appears this problem can be addressed without polluting one's development environment very much.
The Vue forums are in denial about this problem, claiming Vue 3 supports optional chaining. Apparently not, however, in node modules. A post in this thread by atflick on 2/26/2021 was a big help.
Had same issue with Vue 2 without typescript.
To fix this you need to force babel preset to include optional chaining rule:
presets: [
[
'#vue/cli-plugin-babel/preset',
{
include: ['#babel/plugin-proposal-optional-chaining'],
},
],
],
Can also be achieved by setting old browser target in browserslist config.
Most importantly, you need to add your failing module to transpileDependencies in vue.config.js:
module.exports = {
...
transpileDependencies: ['vue-currency-input],
}
This is required, because babel by default will exclude all node_modules from transpilation (mentioned in vue cli docs), thus no configured plugins will be applied.
I had a similar problem. I'm using nuxt but my .babelrc file looks like the below, and got it working for me.
{
"presets": [
["#babel/preset-env"]
],
"plugins":[
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
],
"env": {
"test": {
"plugins": [
["transform-regenerator", {
"regenerator": true
}],
"#babel/plugin-transform-runtime"
],
"presets": [
["#babel/preset-env", {
"useBuiltIns": false
}]
]
}
}
}
I managed to fix the solution by adding these lines to package.json:
...
"scripts": {
"preinstall": "npx npm-force-resolutions",
...
},
"resolutions": {
"acorn": "8.0.1"
},
...

Typescript SyntaxError: Cannot use import statement outside a module (side file containing functions)

I am creating a minecraft bot using mineflayer library. After a bit of work I decided to make code readable and reusable (image of file organisation) and also start using typescript. I have read a lot of stack threads and other articles as this problem is quite popular. However, after trying all of it the problem still persists.
Edit, important change:
I have tried compiling it with tsc bot.ts --resolveJsonModule and then node bot.js. It turns out it works just fine, so now the problem narrows down to configuring WebStorm running options.
Here is what I have already done
package.json "type": "module -> TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for path
tsconfig.json has "esModuleInterop": true
use const util = require('./utils/util') and use util.function() -> same error as in 1st step
Running whole code
As I am using WebStorm, this is what I have in running options: image (just to clarify that I don't run code from terminal)
Recreating problem in simplified environment
bot.ts
import {util} from "./utils/util" // error is thrown right away, so other lines are irrelevant I guess
const mineflayer = require('mineflayer')
const bot = mineflayer.createBot()
util.ts
import * as config from "../config/config_main.json"
export module util {
export function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
export function random(list) {
if (list[0] === list[1]) return list[0];
return Math.floor(Math.random() * (list[1] - list[0])) + list[0];
}
}
config_main.json
{
"bot": {
"username": "username",
"password": "password"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": false,
"skipLibCheck": true
}
}
package.json
{
"type": "module",
"name": "mcbot",
"main": "bot.js",
"scripts": {
"test": "None"
}
}
Related threads
SyntaxError: Cannot use import statement outside a module - "type": "module" doesn't work as well as changing extensions to .mjs isn't viable as I am using typescript
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 - from here tried
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
but the IDE gives me TS2632: Cannot assign to 'util' because it is an import. error.
First, remove type:module from package.json. Then remove module:commonjs from tsconfig.json. Use export default function util () {} syntax. Named exports will also work for local files if you've done the first two steps.
Cause
You are mixing es6 and commonjs. module:commonjs is forcing it to be commonjs whereas esModuleInterop is forcing it to be es6. And type:moduleshows error for es6 and forces to write file extension, remove it first
Warning
Named imports will not work for npm package. Like you can't use
import { something } from "some-package";
Instead, import the default one and then access the named one.
import defaultExport from "some-package";
const something = defaultExport.something
Fixed by changing:
import {util} from "./utils/util"
To:
const util = require('./utils/util')
// or
const { sleep, random, eatAny, clickItem, lookAtEntity} = require('./utils/util')
Afterall I don't know why compiling with tsc had been working well while webstorm was throwing out error. I just changed the import ES6 syntax to require() CommonJS.

"Unexpected token import" when testing Angular with Jest

I've been trying to set up tests for some Angular components, but I keep running into an issue as all of my components use ng-lightning, which results in the following error:
/angular-lightning-test/node_modules/ng-lightning/ng-lightning.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ NgModule } from '#angular/core';
SyntaxError: Unexpected token import
I've tried multiple ways to get this going through Babel, though I'm not sure that should be required as Jest can handle it for every other file using import in this project.
I'm using jest-preset-angular to handle the setup for these tests. You can see the configuration it uses here.
I've created a very small sample project where you can see this error:
https://github.com/humantree/angular-lightning-test
The component is as simple as this:
#Component({
selector: 'badge',
template: '<ngl-badge>{{text}}</ngl-badge>'
}) export class BadgeComponent {
text = 'Test Badge';
}
and the test is as simple as this (I realize an actual test is missing, but the error still occurs before that would happen):
describe('BadgeComponent', () => {
let badge: BadgeComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BadgeComponent],
imports: [NglModule.forRoot()]
});
badge = TestBed.get(BadgeComponent).instance;
});
});
Can anyone see anything that I could add to my Jest configuration (or anything else) that would solve this error?
Note: For what it's worth, I also have these tests set up running in Mocha using mocha-webpack, and am having the exact same issue with that setup.
Thanks!
Try the following:
1) install the following packages: babel-jest, babel-preset-env
2) Add a .babelrc file at the your project root.
{ "presets": ["env"]}
3) Edit your jest.config.js file so babel process ng-lightning
{
"preset": "jest-preset-angular",
"transform": {
"^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!ng-lightning)"
]
}

How to fix 'Module build failed: SyntaxError: Missing class properties transform.'?

In my reactjs component I have this code:
increment = () => {
store.dispatch({type: 'INC'});
}
When I run npm start in the console I get:
Module build failed: SyntaxError: Missing class properties transform.
I installed :
npm install --save-dev babel-plugin-transform-class-properties
And also added this to my .babelrc :
"plugins": [
"transform-class-properties"
],
"presets": [
"es2015",
"react",
"stage-0"
],
How can I resolve this?
Have you seen this other post: Error: Missing class properties transform ?
I had a similar problem, and, as one of the comments on the accepted answer above suggests, I had the presets listed in both my .babelrc file and my webpack.config. I removed the redundant options from my webpack.config and now it runs.

Categories