Support for the experimental syntax 'classProperties' isn't currently enabled - reactjs

While I was setting up React within Django project I came across this error
ModuleBuildError in
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\Users\1Sun\Cebula3\cebula_react\assets\js\index.js: Support
for the experimental syntax 'classProperties' isn't currently enabled (17:9):
15 |
16 | class BodyPartWrapper extends Component {
> 17 | state = {
| ^
18 |
19 | }
20 |
Add #babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the
'plugins' section of your Babel config to enable transformation.
So, I installed #babel/plugin-proposal-class-properties and put this in babelrc
package.json
{
"name": "cebula_react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config prod.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"devDependencies": {
"#babel/cli": "^7.0.0",
"#babel/core": "^7.0.0",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"react-hot-loader": "^4.3.6",
"webpack": "^4.17.2",
"webpack-bundle-tracker": "^0.3.0",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.8"
},
"dependencies": {
"react": "^16.5.0",
"react-dom": "^16.5.0"
}
}
babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
However the error is still existed, What is the problem??

Change
"plugins": [
"#babel/plugin-proposal-class-properties"
]
To
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
This worked for me

First install the: #babel/plugin-proposal-class-properties as dev dependency:
npm install #babel/plugin-proposal-class-properties --save-dev
Then edit your .babelrc so it will be exact like this:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties"
]
]
}
.babelrc file located in the root directory, where package.json is.
Note that you should re-start your webpack dev server to changes take affect.

Solution for webpack project
I just solve this problem by adding #babel/plugin-proposal-class-properties into webpack config plugin.
The module section of my webpack.config.js looks like this
module: {
rules: [
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',
'#babel/react',{
'plugins': ['#babel/plugin-proposal-class-properties']}]
}
}
]
}

{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties"
]
]
}
replace your .babelrc file with above code. it fixed the issue for me.

In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]}
Note: Don't forget to exit the console and reopen before executing the npm or yarn commands.

There are two ways to work with react state:
Option 1:
Just add to package.json:
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
Option 2:
1. Creta a file called .babelrc in the root folder.
Write in .babelrc:
{ "plugins": ["#babel/plugin-proposal-class-properties"] }
Run:
npm i #babel/plugin-proposal-class-properties
3. Run:
npm run dev
or
npm run watch

After almost 3 hours of searching and spending time on the same error, I found that I'm using name import for React:
import { React } from 'react';
which is totally wrong. Just by switching it to:
import React from 'react';
all the error are gone.
I hope this helps someone. This is my .babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
the webpack.config.js
const path = require('path');
const devMode = process.env.Node_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/App.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'App.js'
},
mode: 'development',
devServer: {
contentBase: path.resolve(__dirname, 'public'),
port:9090,
open: 'google chrome',
historyApiFallback: true
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},{
test: /\.(sa|sc|c)ss$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]--[hash:base64:5]',
sourceMap: true
}
},{
loader: 'sass-loader'
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
})
]
}
the package.json
{
"name": "expense-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.1.2",
"#babel/core": "^7.1.2",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.4",
"css-loader": "^1.0.0",
"mini-css-extract-plugin": "^0.4.3",
"node-sass": "^4.9.3",
"react-router-dom": "^4.3.1",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9"
},
"dependencies": {
"normalize.css": "^8.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2"
}
}

Moving the state inside the constructor function worked for me:
...
class MyComponent extends Component {
constructor(man) {
super(man)
this.state = {}
}
}
...
Good Luck...

Install the plugin-proposal-class-properties
npm install #babel/plugin-proposal-class-properties --save-dev
Update your webpack.config.js by adding
'plugins': ['#babel/plugin-proposal-class-properties']}]

I find the problem that my .babelrc was ignored, However I create babel.config.js and add the following:
module.exports = {
plugins: [
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-transform-regenerator',
[
'#babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
},
],
],
presets: [
"#babel/preset-flow",
'module:metro-react-native-babel-preset',
],
};
And it works for me on React Native application, I think this also would help React apps as well.

According to this GitHub issue if you using create-react-app you should copy your .babelrc or babel.config.js configurations to webpack.config.js and delete those.because of htis two line of code babelrc: false,configFile: false, your config in babelrc,.. are useless.
and your webpack.config.js is in your ./node_madules/react-scripts/config folder
I solved my problem like this:
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
'#babel/preset-env', '#babel/preset-react'
],
plugins: ['#babel/plugin-proposal-class-properties'],
.
.
.

I am using the babel parser explicitly. None of the above solutions worked for me. This worked.
const ast = parser.parse(inputCode, {
sourceType: 'module',
plugins: [
'jsx',
'classProperties', // '#babel/plugin-proposal-class-properties',
],
});

I'm using yarn. I had to do the following to overcome the error.
yarn add #babel/plugin-proposal-class-properties --dev

Adding
"plugins": [
[
"#babel/plugin-proposal-class-properties"
]
]
into .babelrc works for me.

yarn add --dev #babel/plugin-proposal-class-properties
or
npm install #babel/plugin-proposal-class-properties --save-dev
.babelrc

For ejected create-react-app projects
I just solved my case adding the following lines to my webpack.config.js:
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
/* INSERT START */
require.resolve('#babel/preset-env'),
require.resolve('#babel/preset-react'),
{
'plugins': ['#babel/plugin-proposal-class-properties']
}
/* INSERTED END */
],

If some one working on monorepo following react-native-web-monorepo than you need to config-overrides.js file in packages/web. you need to add resolveApp('../../node_modules/react-native-ratings'), in that file...
My complete config-override.js file is
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// our packages that will now be included in the CRA build step
const appIncludes = [
resolveApp('src'),
resolveApp('../components/src'),
resolveApp('../../node_modules/#react-navigation'),
resolveApp('../../node_modules/react-navigation'),
resolveApp('../../node_modules/react-native-gesture-handler'),
resolveApp('../../node_modules/react-native-reanimated'),
resolveApp('../../node_modules/react-native-screens'),
resolveApp('../../node_modules/react-native-ratings'),
resolveApp('../../node_modules/react-navigation-drawer'),
resolveApp('../../node_modules/react-navigation-stack'),
resolveApp('../../node_modules/react-navigation-tabs'),
resolveApp('../../node_modules/react-native-elements'),
resolveApp('../../node_modules/react-native-vector-icons'),
];
module.exports = function override(config, env) {
// allow importing from outside of src folder
config.resolve.plugins = config.resolve.plugins.filter(
plugin => plugin.constructor.name !== 'ModuleScopePlugin'
);
config.module.rules[0].include = appIncludes;
config.module.rules[1] = null;
config.module.rules[2].oneOf[1].include = appIncludes;
config.module.rules[2].oneOf[1].options.plugins = [
require.resolve('babel-plugin-react-native-web'),
require.resolve('#babel/plugin-proposal-class-properties'),
].concat(config.module.rules[2].oneOf[1].options.plugins);
config.module.rules = config.module.rules.filter(Boolean);
config.plugins.push(
new webpack.DefinePlugin({ __DEV__: env !== 'production' })
);
return config
};

I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc
{
"presets": [
[
"#babel/preset-react",
{ "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
]
],
"plugins": [["#babel/plugin-proposal-class-properties"]]
}

For the react projects with webpack:
Do: npm install #babel/plugin-proposal-class-properties --save-dev
Create .babelrc (if not present) file in the root folder where package.json and webpack.config.js are present and add below code to that:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
Add below code to the webpack.config.js file:
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ["#babel/preset-env", "#babel/preset-react"]
},
resolve: {
extensions: ['.js', '.jsx']
}
}
Close the terminal and run npm start again.

you must install
npm install #babel/core #babel/plugin-proposal-class-properties #babel/preset-env #babel/preset-react babel-loader
and
change entry and output
const path = require('path')
module.exports = {
entry: path.resolve(__dirname,'src', 'app.js'),
output: {
path: path.resolve(__dirname, "public","dist",'javascript'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
"targets": "defaults"
}],
'#babel/preset-react'
],
plugins: [
"#babel/plugin-proposal-class-properties"
]
}
}]
}
]
}
}

I created a symlink for src/components -> ../../components that caused npm start to go nuts and stop interpreting src/components/*.js as jsx, thus giving that same error. All instructions to fix it from official babel were useless.
When I copied back the components directory everything was BACK TO NORMAL!

Ensure you have not mistakenly imported import BrowserRouter from "react-router-dom/modules/BrowserRouter"; instead of import {BrowserRouter} from "react-router-dom";

If this happens after typescript update, just add useDefineForClassFields: false to tsconfig file.
See: https://www.typescriptlang.org/tsconfig#useDefineForClassFields

Related

Errors when updated babel and webpack version in react project

I am working on a project who was using babel version 5, webpack version 1, and ava version 0.14.0.
After I did some updates when i run npm run build-example i get:
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Multiple configuration files found. Please remove one:
package.json
pathto\react-stars.babelrc
Here's my old package.json
After updates, now I'm using babel version 7.10, webpack version 4.43, and ava version 3.10.1. Here's the updated package.json
{
"name": "react-rating-stars-component",
"version": "2.2.0",
"description": "Simple star rating component for your React projects.",
"main": "dist/react-stars.js",
"repository": "https://github.com/ertanhasani/react-stars",
"babel": {
"presets": [
"react",
"es2015"
]
},
"ava": {
"babel": {
"presets": [
"es2015",
"react"
]
},
"require": [
"babel-register"
]
},
"scripts": {
"build": "babel src --out-dir dist",
"dev": "babel src --out-dir dist --watch",
"build-example": "webpack -p --config webpack.production.config.js",
"dev-example": "webpack-dev-server . --hot --inline"
},
"keywords": [
"star",
"rating",
"react",
"stars",
"rating",
"component",
"raty",
"rate",
"reactjs",
"ratings"
],
"author": "Ertan Hasani",
"license": "ISC",
"devDependencies": {
"ava": "^3.10.1",
"#babel/cli": "^7.10.4",
"babel-loader": "^8.1.0",
"#babel/core": "^7.10.4",
"#babel/plugin-transform-object-assign": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-addons-test-utils": "^15.6.2",
"react-dom": "^16.13.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {}
}
Here's my old webpack.production.config.js
Here's the updated webpack.production.config.js:
'use strict';
var webpack = require('webpack')
module.exports = {
entry: ['./example/index.js'],
output: {
filename: './example/bundle.js',
pathinfo: true
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['#babel/react', '#babel/preset-env']
}
}]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
optimization: {
minimize: false
}
};
Here's my old webpack.config.js
my updated webpack.config.js:
'use strict';
module.exports = {
entry: ['./example/index.js'],
debug: true,
devtool: 'inline-source-map',
output: {
filename: './example/bundle.js',
pathinfo: true
},
module: {
loaders: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['#babel/react', '#babel/preset-env']
}
}]
}
};
I also updated `.babelrc. file:
Here's my old .babelrc file!
my updated .babelrc file:
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
"#babel/plugin-transform-object-assign"
]
}
It seems like you have multiple configurations as mentioned in the error message, I'd suggest removing the following configuration lines from your package.json file and operate your babel configurations exclusively from the .babelrc file in your project root
"babel": {
"presets": [
"react",
"es2015"
]
}

babel core 7.4.4, using all polyfills by default

I was tasked to make one of the mobile apps written in react compatible with opera mini in extreme mode. During the testing, I learned that nothing that is in react code works there, however by including this babel-polyfill before main.js file it actually is working.
I tried to include it to a Webpack so the code is actually converted instead of including a huge library but without success.
package.json file
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/plugin-proposal-class-properties": "^7.10.1",
"autoprefixer": "^8.6.3",
"babel-loader": "^8.0.6",
"copy-webpack-plugin": "latest",
"css-loader": "latest",
"file-loader": "latest",
"html-webpack-plugin": "latest",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "latest",
"postcss-loader": "latest",
"sass-loader": "latest",
"style-loader": "latest",
"url-loader": "latest",
"webpack": "latest",
"webpack-cli": "latest",
"webpack-dev-server": "latest"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0"
}
.babelrc file:
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.js file:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html",
});
module.exports = {
output: {
publicPath: "/",
filename: "js/main.[hash:8].js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.(png|jpg|gif|ico|svg|eot|ttf|woff|woff2)$/,
loader: "url-loader",
options: {
limit: 25000,
outputPath: "assets/",
name: "[name].[hash:8].[ext]",
},
},
{
test: /\.(scss|sass|css)$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
resolve: {
extensions: [".js", ".jsx", ".json"],
},
plugins: [
htmlPlugin,
new MiniCssExtractPlugin({
filename: "css/style.[hash:8].css",
}),
],
devServer: {
historyApiFallback: {
rewrites: [{ from: /^\/$/, to: "/index.html" }],
},
},
};
How these can be modified so I don't have to include entire babel-polyfill.min.js and Webpack + babel will actually convert the code to work?
--EDIT
I had success with following changes:
package.json file
...
"browserslist": [
"dead"
],
...
.babelrc file:
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": 3
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
[
"#babel/transform-runtime",
{
"corejs": 3
}
]
]
}
webpack.config.js file:
...
entry: "./src/index.js",
...
Once this setup is in place, i have to manually include import "core-js"; at the top of every file that is part of project so for example:
index.js
App.js
components/events.jsx
components/popup.jsx
and so on...
is there a way to avoid that inclusion by some configuration in webpack or babel ? (i tried "useBuiltIns": "usage" instead of entry but it doesnt include all needed polyfills)
I was gonna suggest you drop babel-polyfill since it's deprecated as of 7.4.0 but then saw your edit.
If you want to avoid importing core-js everywhere you should use "useBuiltIns": "usage".
I think the reason it doesn't polyfill everything is because your browserslist query doesn't match to opera mini according to (https://browserl.ist/?q=dead), you should specify it, something like:
...
"browserslist": [
"dead",
"op_mini all"
],
...

Error webpack dev server when using yarn workspaces

I got an error "webpack-dev-server error cannot find module 'webpack-cli/bin/config/config-yargs'" when installing webpack, webpack-cli and webpack-dev-server in a yarn workspace.
Doesn't have this issue when installing them in a repo.
I checked the node_modules in the root and in the child. It appears that this config/config-yargs file is installed in the node_module of the CHILD but not in the ROOT one.
I have to copy it manually from child to root to make this works.
Is there a way to install this correctly ?
My root package.json :
{
"private": true,
"workspaces": [
"packages/server",
"packages/front", <-- webpack has been installed her
],
"name": "test",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
part of child package.json
{
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-react": "^7.8.3",
"#babel/preset-typescript": "^7.8.3",
"typescript": "^3.7.5",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
webpack.config.js
const path = require("path");
const rules = [
{
test: /\.(tsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.css$/,
loader: ["style-loader", "css-loader"],
},
];
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
target: "web",
mode: "development",
entry: "./src/examples/index.tsx",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
module: { rules },
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
devServer: {
contentBase: "./",
port: 5000,
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "react typescript babel webpack boilerplate",
template: "index.html",
}),
],
};
The solution is to use embedded devServer with webpack serve command, read about it here
https://webpack.js.org/guides/development/#using-webpack-dev-server
You might have another problem with workspaces and the solution is nohoist, read about it here
https://classic.yarnpkg.com/blog/2018/02/15/nohoist/
Nohoist for me was not working until I figured out it should be used on root package.json and not in child, here is the version that worked for me
"workspaces": {
"packages": [
"package-1",
"package-2",
],
"nohoist": [
"**/webpack",
"**/webpack/**",
"**/webpack-dev-server",
"**/webpack-dev-server/**",
"**/#webpack-cli",
"**/#webpack-cli/**",
"**/webpack-cli",
"**/webpack-cli/**"
]
},
You might also want to delete node_modules as usual :)

React types files not working in React TypeScript (.tsx) file - Throwing ESLint errors for React Component

I have a React build configuration using Webpack, ESlint, Prettier and TypeScript.
When I run the build it looks like I'm getting TypeScript linting errors that should be nullified by the #typings/react or #typings/react-dom packages.
Looking at the documentation I shouldn't need to define accessibility modifiers or return types for React Components: https://www.typescriptlang.org/docs/handbook/jsx.html
This seems like the same issue as here: Missing return type on function - in react (typescript) code
but installing the typings packages hasn't resolved the issue for me. Please note, I have also tried removing the #typings/react package as the #typings/react-dom has this as a dependency and this doesn't resolve the issue.
Webpack config
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const path = require('path');
const createWebpackConfig = () => {
const isProd =
process.env &&
process.env.NODE_ENV &&
process.env.NODE_ENV === 'production';
return {
entry: ['#babel/polyfill', './index.tsx'],
mode: isProd ? 'production' : 'development',
module: {
rules: [
{
enforce: 'pre',
test: /(\.jsx|\.js|\.ts|\.tsx)$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /(\.jsx|\.js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
},
{
test: /(\.tsx|\.ts)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-typescript',
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
}
]
},
resolve: {
modules: [path.resolve(__dirname, '/'), 'node_modules'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
enforceExtension: false
},
target: 'web',
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor'
},
main: {
name: 'main'
}
}
}
},
output: {
path: path.join(__dirname, 'bundles'),
filename: '[name].app.js',
chunkFilename: '[name].bundle.js',
pathinfo: true
},
plugins: [
new CaseSensitivePathsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(isProd ? 'production' : 'development')
}
})
]
};
};
module.exports = createWebpackConfig;
ESLint config
{
"parser": "#typescript-eslint/parser", // Specifies the ESLint parser
"extends": [
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended", // Uses the recommended rules from the #typescript-eslint/eslint-plugin
"prettier/#typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from #typescript-eslint/eslint-plugin that would conflict with prettier
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
"parserOptions": {
"ecmaVersion": 10, // Allows for the parsing of modern ECMAScript features
"sourceType": "module", // Allows for the use of imports
"jsx": true
},
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"endOfLine": "auto"
}
]
}
}
tsconfig.json
{
"compilerOptions": {
"module": "esnext",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"jsx": "preserve"
},
"exclude": ["node_modules"]
}
package.json
{
"name": "reacttypescripttest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "cross-env NODE_ENV=development webpack --config ./webpack.config.js --progress --colors --watch --display-error-details"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-proposal-object-rest-spread": "^7.5.5",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "^7.0.0",
"#babel/preset-typescript": "^7.3.3",
"#types/react": "^16.8.24",
"#types/react-dom": "^16.8.5",
"#typescript-eslint/eslint-plugin": "^1.13.0",
"#typescript-eslint/parser": "^1.13.0",
"babel-loader": "^8.0.6",
"case-sensitive-paths-webpack-plugin": "^2.2.0",
"cross-env": "^5.2.0",
"eslint": "^6.1.0",
"eslint-config-prettier": "^6.0.0",
"eslint-loader": "^2.2.1",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-react": "^7.14.3",
"mini-css-extract-plugin": "^0.8.0",
"prettier": "^1.18.2",
"prettier-eslint": "^9.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"typescript": "^3.5.3",
"webpack-cli": "^3.3.6"
},
"devDependencies": {
"webpack": "^4.39.1"
}
}
File causing error (index.tsx)
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return <div>Running!</div>;
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Errors
5:3 error Missing accessibility modifier on method definition render #typescript-eslint/explicit-member-accessibility
5:9 warning Missing return type on function #typescript-eslint/explicit-function-return-type
The first error Missing accessibility modifier on method definition render is saying that you did not declare your render method as public or private or any other type (more reading on types. When working with Typescript all class methods need to have be declared accordingly, depending if you want to have them accessible outside your class instance or not. For render method it should be public. Code below should work nicely for you:
public render() {
return <div>Running!</div>;
}
When it comes the 2nd error your're having, it means that your linter expects the render method to have declared what's the output of its' execution. The correct type for render method is React.ReactNode, so your final code should look like below (assuming you're not importing ReactNode in the import statement earlier)
public render(): React.ReactNode {
return <div>Running!</div>;
}
Edit 1
Even if TS itself doesn't require all these annotations, the linter you're using does. See their default rules- as you can see, the rules you're having trouble with are not turned off. The solution there would be disabling them in your app eslint config, like below:
"rules": {
"#typescript-eslint/explicit-function-return-type": "off",
"#typescript-eslint/explicit-member-accessibility": "off"
}
If anyone is running into this AND using a tsx file already. Makre sure that you've configured vscode to associate tsx files with TypescriptReact and not just Typescript. When the tsx file is open, bottom right click on Typescript and set association.

Unable to build ES6 version of my React App with webpack and babel-preset-env [duplicate]

This question already has answers here:
Webpack + Babel error
(2 answers)
Closed 5 years ago.
I decided to rewrite my existing React App from ES5 to ES6. Below is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ToDoList from './to-do-list.jsx';
//Put the components into HTML
ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
However when I try to build with webpack and launch the app I get the error that:
ERROR in ./src/app/index.js
Module parse failed: /home/sam/devzone/github/simple-react-todo-app/src/app/index.js Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
|
| //Put the components into HTML
| ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
I have selected babel-preset-env instead of babel-preset-es2015, but I highly doubt that this is the cause. Below are snapshots of my package.json and my webpack.config.js respectively.
package.json
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --content-base src/ --inline --hot --port 1234"
},
...
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.7",
"eslint": "^4.7.2",
"eslint-plugin-react": "^7.4.0",
"style-loader": "^0.18.2",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
],
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};
As it might be evident that I did a bit trial and error myself, but I seem to be totally lost now.
The app folder structure and other relevant files can be seen inside my repo here.
Any pointers would be appreciated.
Your webpack's config is wrong (it's old config from Webpack 1)
You should change it to:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
options: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};
Just change
test: /\.jsx?$/,
To
test: /.(js|jsx)?$/,

Resources