ECMAScript如今已经到2018了,每次都有新的语言特性,为了可以使用这些新特性,咱们能够经过安装babel插件方式得到支持。 javascript
babel插件列表 java
下面是安装@babel/plugin-proposal-class-properties
的过程,该插件实现了类里定义属性的语言特性。node
yarn add -D @babel/plugin-proposal-class-properties
加入代码plugins: ['@babel/plugin-proposal-class-properties']
,最终的babel.config.js内容以下react
module.exports = { "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry", "targets": { "browsers": [ "cover 99.5% in CN" ] } } ], "@babel/preset-react" ], plugins: ['@babel/plugin-proposal-class-properties'] }
如今咱们就能够在类里定义属性了es6
咱们在main.js里随便写一个类web
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」。babel
eslint报错了app
ERROR in ./app/main.js Module 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可以识别该特性。dom
yarn add -D babel-eslint
加入新的配置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
,发现以前的报错不见了。