create-react-app(簡稱cra)已經更新之2.0.3版本, babel也更新至7.x版本, JavaScript裝飾器語法雖然還不是標準, 可是藉助於babel, 也能在項目裏愉快的玩耍.react
cra2.0時代如何啓用裝飾器語法呢? 咱們依舊採用的是react-app-rewired, 經過劫持webpack cofig對象, 達到修改的目的.webpack
yarn add react-app-rewired
修改package.jsongit
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }
安裝裝飾器語法所需的babel插件, 也能夠順帶升級babel-coregithub
yarn add @babel/plugin-proposal-decorators metro-react-native-babel-preset -D
在項目根目錄下建立.babelrc, config-overrides.js文件web
// .babelrc { "presets": ["module:metro-react-native-babel-preset"], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ] } // config-overrides const { getBabelLoader } = require('react-app-rewired'); const path = require('path'); module.exports = function override(config, env) { const babelLoader = getBabelLoader(config.module.rules); const pwd = path.resolve(); babelLoader.include = [path.normalize(`${pwd}/src`)]; // use babelrc babelLoader.options.babelrc = true; return config; };
原理就是劫持了config對象, 對其babel規則進行簡單的修改.
附上完整的package.jsonjson
{ "name": "my-react-project", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.5.2", "react-app-rewired": "^1.6.2", "react-dom": "^16.5.2", "react-scripts": "2.0.5" }, "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }, "eslintConfig": { "extends": "react-app" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ], "devDependencies": { "@babel/plugin-proposal-decorators": "^7.1.2", "metro-react-native-babel-preset": "^0.48.1", "webpack-bundle-analyzer": "^3.0.3" } }