I am trying to tidy some React code by using a static property of the class something like
class X extends React.Component {
static counter = 0
...
render() {
return( <div>{X.counter}</div>)
}
}
The build fails with unexpected token static counter = 0
My .babelrc is
{
"plugins": ["transform-class-properties", "transform-react-jsx" ]
}
and my package.json (using Webpack to build) is ...
{
"name": "js",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-latest": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"webpack": "^4.12.2",
"webpack-dev-server": "^3.1.4"
},
"scripts": {
"dev": "webpack-dev-server --inline --hot --no-info --env dev",
"build:prod": "webpack --env prod --progress --profile --colors",
"build:dev": "webpack --env dev --progres --profile --colors"
},
"dependencies": {
"css-loader": "^1.0.0",
"react-meter-bar": "^1.0.2",
"react-modal": "^3.5.1",
"react-websocket": "^2.0.0",
"style-loader": "^0.21.0",
"webpack-cli": "^3.0.8"
}
}
Can anyone help ?
I solved the issue by adding the plugin to the Webpack.config.js and using babel-loader - this is probably due to my lack of knowledge how Webpack works ...
const path = require('path');
module.exports = {
mode: 'development',
context: path.join(__dirname, 'src'),
entry: [
'./app.js',
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets:['react'],
plugins: ["transform-class-properties"]
}
}
],
},
{
test:/\.css$/,
use:['style-loader','css-loader'],
},
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};