Webpack预设:“ env”时,缺少的类属性会转换

时间:2018-09-28 06:05:25

标签: reactjs webpack babel babel-preset-env

我正在webpack-dev-server上测试React项目。我想使用classfield syntax,但在状态初始化时出错。

client:162 ./src/containers/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Missing class properties transform.
2 | 
3 | class App extends Component {
4 |     state = {
  |     ^
5 |         count: 0
6 |     }
7 |     // constructor(props) {

我找到了预设为此"presets": ["es2015", "stage-0", "react"]的解决方案。但是我正在使用“ env”预设。我认为“ env”预设支持所有babel阶段。我必须更改预设吗?

App.js

class App extends Component {

state = {
    count: 0
}

render() {
    return (
      <div>
          <input defaultValue={this.state.count} />
      </div>
    );
  }
}

export default App;

package.json

{
  "name": "redux",
  "version": "1.0.0",
  "description": "",
  "main": "counter.js",
  "dependencies": {
    "@types/react": "^16.4.14",
    "babel": "^6.23.0",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-register": "^6.26.0",
    "http": "0.0.0",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "webpack": "^4.19.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.9"
  },
  "scripts": {
    "devserver": "webpack-dev-server --open --progress"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-plugin-transform-class-properties": "^6.24.1"
  }
}

.babelrc

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

.webpack.config.js

const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/dist/',
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                include: path.join(__dirname),
                exclude: /(node_modules)|(dist)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

.babelrc

{
  "presets": ["env", "react", "stage-2"]
}

package.json

"devDependencies": {
  "babel-cli": "^6.26.0",
  "babel-core": "^6.26.3",
  "babel-loader": "^7.1.4",
  "babel-preset-env": "^1.7.0",
  "babel-preset-react": "^6.24.1",
  "babel-preset-stage-2": "^6.24.1",
  ...

使用.babelrc文件时,在webpack.config.js中,我们可以像这样简单地进行配置:

{
   test: /\.js$/,
   use: ['babel-loader']
}

希望这会有所帮助。