create-react-app / babel / binding state and functions - javascript

Thank you for your time. I have the same issue as in this issue re parsing error - unexpected token = eslint on (originally state - which was fixed by putting in constructor, now) handleClick. New project and think this error will continue through the rest of the project.
class Header extends Component {
constructor() {
super();
this.state = {
activeItem: "home"
};
}
handleClick = (event, { name }) => this.setState({ activeItem: name });
I am new to react, and apologise if this is a simple question. Project was installed with create-react-app, there is no babelrc file, the eslint is as follows.
module.exports = {
env: {
browser: true,
es2021: true,
jest: true,
},
extends: ["plugin:react/recommended", "airbnb", "prettier"],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: "module",
},
plugins: ["react"],
rules: {},
};
From what i have read, I have to install babel to the project, and customise the config to accept state = { activeItem: "home" }; if I want to set state / functions outside the constructor and need to use a 'basic syntax', for fixing the function, i am not sure what that basic syntax is. Help?! I think the course of action is to create a babelrc config file, but am not sure why if it is already installed with create-react-app and do not want to install a bunch of dependencies unless i have to.
Thank you for your patience.

It looks like you need to fix up your ESlint config a bit:
npm install eslint #babel/core #babel/eslint-parser --save-dev
and then add
parser: "#babel/eslint-parser",
to the top level of your ESLint config. Alternatively you could use the default Create React App ESLint config by removing yours, which should be all set already.

Related

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"
},
...

Module build failed - no ESLint configuration found after import

I have worked on a vue project which I created using vue cli. Because of this, eslint is also included in the project. Up until now I haven't done much with eslint. If I understood correctly, eslint helps with stylistic errors, semantic errors etc in the code to identify potential problems.
I only rarely used // eslint-disable-next-line if there was e.g. a console.log clashing with the rules.
Now I wanted to include some new javascript code into the project. This code comes from someone else, so I cloned the repo and then just imported it in my main.js via a relative path to the folder/file that I have cloned. I think this was okay. However now I get some problems with eslint as the imported file has no config for eslint.
This is the exact error originating from the import:
Module build failed (from ./node_modules/eslint-loader/index.js):
Error: No ESLint configuration found
I am not sure what to do now, even though I already searched for the error.
I only saw some config for eslint in the package.json, I think. If it would help to have its content or something else, please say so and I will add it!
How can I tackle this problem? Thanks in advance!
This might be a long shot, but this is the .eslintrc.js file I shove into all my react projects at the root directory to get rid of that error. You'll want to change some of the settings but this is the basic structure.
module.exports = {
parser: 'babel-eslint',
env: {
browser: true,
commonjs: true,
es6: true,
node: true,
jest: true,
},
parserOptions: {
ecmaVersion: 2020,
ecmaFeatures: {
jsx: true,
},
sourceType: 'module',
},
plugins: ['react', 'react-hooks'],
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:json/recommended',
'prettier',
],
settings: {
react: {
version: 'detect',
},
},
rules: {
'react/prop-types': ['off'],
'react/no-unescaped-entities': ['error', { forbid: ['>', '}'] }],
},
};

How can I avoid losing my class name when I bundle source with webpack in production mode?

When I bundle code below in development mode and run abc(),
class Foo { ... }
export function abc () { return new Foo(); }
I got Foo { ... }.
But bundle with production mode, I got something like k { ... } and I lost information about class name.
How can I avoid this?
In other words, I want to minify code except class name because I want to use source as a library with npm install my-github-repository and require("abc").
webpack configure sourcemap and then use the uglifyjs-webpack-plugin package to set the output souremap to keep the class name and function name
new UglifyJsPlugin({
sourceMap: true,
parallel: 4,
uglifyOptions: {
keep_classnames: true,
keep_fnames: true
}
})

How to extend CRA ESLint rules with EXTEND_ESLINT environment variable

Recently Facebook's Create React App (CRA) released a new feature which allows you to extend their base ESLint rules.
We recognise that in some cases, further customisation is required. It
is now possible to extend the base ESLint config by setting the
EXTEND_ESLINT environment variable to true.
Setting Up Your Editor
Here is the example given but with no detail such as filename or what "shared-config" is.
{
"eslintConfig": {
"extends": ["react-app", "shared-config"],
"rules": {
"additional-rule": "warn"
},
"overrides": [
{
"files": ["**/*.ts?(x)"],
"rules": {
"additional-typescript-only-rule": "warn"
}
}
]
}
}
The feature is enabled by added an environment variable.
EXTEND_ESLINT=true
but on the documentation page it also doesn't give any information how to use it - Advanced configuation
I've added their example code to my build in a file called .eslintrc.json but I get a build error:
"Error: ESLint configuration in .eslintrc.json is invalid: - Unexpected top-level property "eslintConfig"."
Has anyone got this working? Does the file need to export a module?
While unclear from the Create-React-App documentation, the example they give is as if the project's ESLint configuration was inside the eslintConfig property of the package.json file.
You need to configure ESLint as described in its documentation. So if you choose the .eslintrc.json way, it must be a valid ESLint configuration file, which doesn't have a eslintConfig property.
The only things that matter in the example are:
they're extending from "react-app" before any other configuration
any additional rule is set to "warn" to avoid stopping the project from building
if using TypeScript, place the specific TS related configuration in the "overrides" section.
A simple .eslintrc.js (notice the extension) configuration file for a CRA project using TypeScript could be as follows:
const defaultRules = [
'react-app',
'eslint:recommended',
// any other plugins or custom configuration you'd like to extend from.
];
module.exports = {
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
node: true,
es6: true,
jest: true,
},
extends: defaultRules,
rules: {
'array-callback-return': 'warn',
'consistent-return': 'warn',
'default-case': 'warn',
// etc.
},
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
plugins: ['#typescript-eslint'],
extends: [
...defaultRules,
'plugin:#typescript-eslint/recommended',
// any other TypeScript specific config (from a plugin, or custom)
],
rules: {
'#typescript-eslint/no-explicit-any': 'warn',
'#typescript-eslint/no-unused-vars': 'warn',
'#typescript-eslint/no-unused-expressions': 'warn',
// etc.
},
},
],
settings: {
react: {
// React version. "detect" automatically picks the version you have installed.
version: 'detect',
},
},
};

Svelte and ESLint

A few days ago I decide to migrate frontend application to Svelte from Vanilla JS (specific reasons).
And at first I decided to configure eslint config. I spent about 3 hours to find an answer of how to integrate svelte into eslint and I didn't find nothing besides this plugin
Here is my eslint config
module.exports = {
extends: ['eslint:recommended', 'prettier'],
parserOptions: {
ecmaVersion: 2019,
sourceType: 'module'
},
env: {
es6: true,
browser: true
},
plugins: [ 'svelte3' ],
overrides: [
{
files: '*.svelte',
processor: 'svelte3/svelte3'
}
],
globals: {
"module": true,
"process": true,
},
rules: {
// ...
},
settings: {
// ...
}
};
Here is dev. dependencies of package.json:
Where is contains my svelte components:
I have non formatted code:
And what tell me eslint:
After eslint . and eslint . --fix commands the code of svelte component still non formatted
I'm sure that I'm doing something wrong, hope on your help.
To use eslint with svelte 3, all you have to do is :
npm install \
eslint \
eslint-plugin-import \
eslint-plugin-node \
eslint-plugin-promise \
eslint-plugin-standard \
eslint-plugin-svelte3 \
--save-dev
Add this script in package.json :
"scripts": {
"lint": "eslint . --ext .js,.svelte --fix"
},
And add a file .eslintrc.js next to the package.json file :
module.exports = {
parserOptions: {
ecmaVersion: 2019,
sourceType: 'module'
},
env: {
es6: true,
browser: true,
node: true
},
extends: [
'eslint:recommended'
],
plugins: [
'svelte3'
],
ignorePatterns: [
'public/build/'
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3'
}
],
rules: {
// semi: ['error', 'never'] // uncomment if you want to remove ;
},
settings: {
// ...
}
}
Then you can run npm run lint to fix your files.
ESLint (and linters in general) are good for finding and potentially fixing things that violate certain rules, but ESLint isn't primarily a formatting tool.
To format Svelte files automatically, you'll have better luck with Prettier and the Svelte plugin for Prettier.
If you're using Visual Studio Code, you can install the Svelte for VS Code plugin which will be able to format your files automatically when you save them (assuming you have formatOnSave turned on).
I assume you are using VSCode by looking at your screenshots. At the documentation's page of the plugin you mention, there's an explanation of how to configure it in your code editor. ( https://github.com/sveltejs/eslint-plugin-svelte3/blob/master/INTEGRATIONS.md )
You'll need the ESLint extension installed.
Unless you're using .html for your Svelte components, you'll need to configure files.associations to associate the appropriate file extension with the html language. For example, to associate .svelte, put this in your settings.json:
{
"files.associations": {
"*.svelte": "html"
}
}
Then, you'll need to tell the ESLint extension to also lint files with language html and to enable autofixing where possible. If you haven't adjusted the eslint.validate setting, it defaults to [ "javascript", "javascriptreact" ], so put this in your settings.json:
{
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "html",
"autoFix": true
}
]
}
If you are using an extension that provides Svelte syntax highlighting, don't associate *.svelte files with the html language, and instead enable the ESLint extension on "language": "svelte".
Reload VS Code and give it a go!

Categories