ECMAScript现在已经到2018了,每次都有新的语言特性,为了能够使用这些新特性,我们可以通过安装babel插件方式获得支持。

babel插件列表

下面是安装@babel/plugin-proposal-class-properties的过程,该插件实现了类里定义属性的语言特性。

安装依赖

yarn add -D @babel/plugin-proposal-class-properties

修改babel.config.js

加入代码plugins: ['@babel/plugin-proposal-class-properties'],最终的babel.config.js内容如下

module.exports = {  "presets": [    [      "@babel/preset-env",      {        "useBuiltIns": "entry",        "targets": {          "browsers": [            "cover 99.5% in CN"          ]        }      }    ],    "@babel/preset-react"  ],  plugins: ['@babel/plugin-proposal-class-properties']}

测试

现在我们就可以在类里定义属性了

我们在main.js里随便写一个类

import ReactDOM from "react-dom";import React from "react";function App() {    return (        <div className="App">            <h1>Hello World</h1>        </div>    );}const rootElement = document.getElementById("root");ReactDOM.render(<App/>, rootElement);//定义Person类class Person {  //定义类的属性  name='zhangsan';  logName(){    console.log(this.name);  }}new Person().logName();

然后就能看到控制台打印了「zhangsan」。

eslint问题

eslint报错了

ERROR in ./app/main.jsModule Error (from ./node_modules/eslint-loader/index.js):/Users/jevi/projects/react-project/app/main.js  17:7  error  Parsing error: Unexpected token =✖ 1 problem (1 error, 0 warnings)

很明显是因为eslint不认识【类里定义属性】的语法特性。
接下来我们让eslint能够识别该特性。

安装babel-eslint

yarn add -D babel-eslint

修改.eslintrc.js

加入新的配置parser: "babel-eslint",最终的.eslintrc.js如下

module.exports = {  'env': {    'browser': true,    'es6': true,  },  'extends': ["eslint:recommended","plugin:react/recommended","google"],  'globals': {    'Atomics': 'readonly',    'SharedArrayBuffer': 'readonly',  },  'parserOptions': {    'ecmaFeatures': {      'jsx': true,    },    'ecmaVersion': 2018,    'sourceType': 'module',  },  'plugins': [    'react',  ],  'rules': {  },  "settings": {    "react": {      "version": "detect"    }  },  parser: "babel-eslint"};

然后重新启动webserveryarn start:dev,发现之前的报错不见了。