先npm run inject暴露webpack
我们用create-react-app创建的项目时,并不能使用修饰器语法
修饰器语法是ES.next 2阶段特性。
我在使用mobx时需要用@observable让属性被观测和组件观测变化@observer
使用路由时需要withRouter将路由信息传递个组件的props对象上等都需要用到修饰器语法。
npm run inject启动后配置.babelrc文件
npm install --save-dev babel-preset-env
npm install --save-dev babel-plugin-transform-decorators-legacy
npm install --save-dev babel-plugin-transform-class-properties
{
"presets": ["env","react"],
"plugins": ["transform-decorators-legacy","transform-class-properties"]
}
babel-preset-env取代babel-preset-2015
由于.babelrc文件会覆盖脚手架的配置文件,所以presets要添加react
transform-decorators-legacy是修饰器配置
transform-class-properties是类中定义实例属性的新方法,以前定义实例的属性只能写在constructor中,现在可以直接写在外面
//以前定义实例属性写在constructor
class Test extends React.Component{
constructor(props){
super(props)
this.state = {}
}
}
//现在定义实例属性可以直接写在外面
class Test extends React.Component{
state = {}
}
另一种简单的配置
npm install babel-preset-stage-2 --save-dev
npm install babel-preset-react-native-stage-0 --save-dev
{
"presets": ["react-native-stage-0/decorator-support"]
}