无法使用Webpack和Babel构建的React Class属性

时间:2018-07-17 16:53:44

标签: reactjs webpack babel class-properties

我正在尝试通过使用类似此类的静态属性来整理一些React代码

class X extends React.Component {
   static counter = 0
   ...
   render() {
     return( <div>{X.counter}</div>)
   }
}

构建失败,带有意外令牌static counter = 0

我的.babelrc是

{
"plugins": ["transform-class-properties", "transform-react-jsx" ]
}

和我的package.json(使用Webpack构建)是...

{
  "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"
  }
}

任何人都可以帮忙吗?

我通过将插件添加到Webpack.config.js并使用babel-loader解决了该问题-这可能是由于我不了解Webpack的工作原理...

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'),
    ],
  },
};

0 个答案:

没有答案