详解create-react-app 2.0版本如何启用装饰器语法
2019/6/26 23:23:52
本文主要是介绍详解create-react-app 2.0版本如何启用装饰器语法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
create-react-app(简称cra)已经更新之2.0.3版本, babel也更新至7.x版本, JavaScript装饰器语法虽然还不是标准, 但是借助于babel, 也能在项目里愉快的玩耍.
cra2.0时代如何启用装饰器语法呢? 我们依旧采用的是react-app-rewired, 通过劫持webpack cofig对象, 达到修改的目的.
yarn add react-app-rewired
修改package.json
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }
安装装饰器语法所需的babel插件, 也可以顺带升级babel-core
yarn add @babel/plugin-proposal-decorators metro-react-native-babel-preset -D
在项目根目录下创建.babelrc, config-overrides.js文件
// .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.json
{ "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" } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于详解create-react-app 2.0版本如何启用装饰器语法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-26React入门教程:从零开始搭建你的第一个React应用
- 2024-12-25Vue2入门教程:轻松掌握前端开发基础
- 2024-12-25Vue3入门指南:快速搭建你的第一个Vue3项目
- 2024-12-25JS基础知识入门教程
- 2024-12-25React基础知识详解:从入门到初级应用
- 2024-12-25Vue3基础知识详解与实战指南
- 2024-12-25Vue3学习:从入门到初步掌握
- 2024-12-25Vue3入门:新手必读的简单教程
- 2024-12-23【JS逆向百例】爱疯官网登录逆向分析
- 2024-12-21Vue3教程:新手入门到实践应用