This question already has answers here:
Unexpected token '=' in React Component [duplicate]
(2 answers)
Closed 4 years ago.
I have the following .babelrc in the root directory of a React project that I build with Webpack (created with create-react-app).
{
"presets": ["react-app", "env"],
"plugins": [
[
"react-intl",
{
"messagesDir": "./public/messages/"
}
]
]
}
When I run the build, I get the following error
Syntax error: Missing class properties transform.
1 | export default class ValidationUtils {
> 2 | static isPhoneNumber = 'whatever'
| ^
3 | }
If I remove "env" from the presets list I no longer get this error, but instead, I get an error that complains about the usage of an ES6 import in a script that is run as part of the build
/apps/my-app/scripts/mergeMessages.js:3
import * as fs from "fs";
^^^^^^
SyntaxError: Unexpected token import
Is there some presets setting (or anything else) that will overcome both of these issues?
You need the transform-class-properties plugin: https://babeljs.io/docs/en/babel-plugin-transform-class-properties
You babelrc will then look like this:
{
"presets": ["react-app", "env"],
"plugins": [
[
"react-intl",
{
"messagesDir": "./public/messages/"
}
],
"transform-class-properties"
]
}
Related
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.
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"
},
...
This question already has an answer here:
Typescript see the one type in reqursive git submodule as different types
(1 answer)
Closed 6 months ago.
In my package.json, module1 version 1 and module2 version 2 are listed as dependencies.
In addition, package module1 has module2 version 1 as its dependencies
And when I use module2 in my code
const { SomeClass } = require('module2');
vscode and tsc signal me
Namespace '"{project_path}/node_modules/module1/node_modules/module2/dist/index"' has no exported member 'SomeClass'
How can I make tsc use exactly the version of the module that is specified in my root package.json?
After adding this code to my tsconfig.json the problem was solved
{
"compilerOptions": {
...,
"paths": {
"*": [
"./node_modules/*"
]
}
},
...
}
I am working on a Next.js project using TypeScript and for testing I use Jest and React Testing Lib. However, I encounter a SyntaxError: Cannot use import statement outside a module for components where I import rehype-raw.
As far as I understand this, Jest does not support ES6 so node_modules may need to be transformed. This can be configured using transformIgnorePatterns. For example if rehype-raw is causing this error using "transformIgnorePatterns": ["node_modules/(?!rehype-raw)/"] should allow transformation of the rehype-raw but no other module. And thus solve this error.
However, this does not work for me. But idk why and how I can solve this. No suggested solution I have found could solve this problem. I have attached my error output, jest.config.js and babel.rc file below.
Error output
FAIL test/pages/companies/[id].test.tsx
● Test suite failed to run
Jest encountered an unexpected token
[...]
Details:
/path/frontend-job/node_modules/rehype-raw/index.js:7
import {raw} from 'hast-util-raw'
^^^^^^
SyntaxError: Cannot use import statement outside a module
3 | import Image from 'next/image';
4 | import { Remark } from 'react-remark';
> 5 | import rehypeRaw from 'rehype-raw';
| ^
6 | import rehypeSanitize from 'rehype-sanitize';
7 | import { logError } from '#utils/logger';
8 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (components/markdown/JobMarkdown.tsx:5:1)
jest.config.js
const { resolve } = require('path');
module.exports = {
roots: ['<rootDir>'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
setupFiles: ['<rootDir>/test/setup.js'],
testPathIgnorePatterns: ['<rootDir>[/\\\\](node_modules|.next)[/\\\\]'],
transform: {
'^.+\\.(ts|tsx)$': 'babel-jest',
},
transformIgnorePatterns: [
'node_modules/(?!rehype-raw)/',
],
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
moduleNameMapper: {
// Force mocks: https://github.com/facebook/jest/issues/4262
'#api/axios': '<rootDir>/test/__mocks__/axios.js',
// Normal module aliases
'\\.(css|less|sass|scss)$': 'identity-obj-proxy',
'\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js',
'^#test/(.*)$': resolve(__dirname, './test/$1'),
'^#test/faker/(.*)$': resolve(__dirname, './test/faker/$1'),
'^#components/(.*)$': resolve(__dirname, './components/$1'),
'^#pages/(.*)$': resolve(__dirname, './pages/$1'),
'^#utils/(.*)$': resolve(__dirname, './utils/$1'),
'^#api/(.*)$': resolve(__dirname, './api/$1'),
'^#store/(.*)$': resolve(__dirname, './store/$1'),
},
testEnvironment: 'jsdom',
};
babel.rc
{
"presets": ["next/babel"]
}
Did you already use type:"module" in package.json?
Next has already out-of-the-box support for Jest, I'd suggest you follow the steps provided in the docs.
I am using JSDOC and all it supported npm plugins to create nice documentation. Getting hard time when jsdoc is running and parsing JSX file it always throws error as below near = sign
SyntaxError: unknown: Unexpected token
export default class SaveDesign extends Component {
static displayName = 'SaveDesign';
}
conf.json file
{
"source": {
"include": [ "src/app/test.js", "src/app/components/Modals/Template/SaveDesign.jsx"],
"exclude": [ "src/fonts", "src/icons", "src/less", "src/vector-icon" ],
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins": ["node_modules/jsdoc-babel"],
"babel": {
"extensions": ["js", "es6", "jsx"],
"presets": ["es2015"]
},
"jsx": {
"extensions": ["js", "jsx"]
}
}
Class properties aren't part of the ES2015 spec, so they're not part of the ES2015 Babel preset either. The proposal to add class properties to the language is currently at Stage 3 of the standardization process, so you need the Stage 3 preset.
https://babeljs.io/docs/plugins/preset-stage-3/
Alternatively, you could just install the class properties plugin on its own:
https://babeljs.io/docs/en/babel-plugin-proposal-class-properties
As stage-2 , stage-3 or any other stage preset are removed in babel 7 or newer so you have to add plugin separately.
Please use "require()" for importing plugin otherwise it wont work.
Here is the .bablerc file -
module.exports = {
plugins: [
[require("#babel/plugin-proposal-class-properties"), { loose: false }]
],
presets: ["#babel/preset-env", "#babel/preset-react"]
};
#Joe thanks yes the plugin which you mentioned will help to solve the problem. In my case the way I solved it was by making sure to have all .babelrc dependency copied to jsdoc babel property as well I was missing this piece which was giving me all the errors.