create-react-app(簡(jiǎn)稱cra)已經(jīng)更新之2.0.3版本, babel也更新至7.x版本, JavaScript裝飾器語(yǔ)法雖然還不是標(biāo)準(zhǔn), 但是借助于babel, 也能在項(xiàng)目里愉快的玩耍.
創(chuàng)新互聯(lián)技術(shù)團(tuán)隊(duì)10多年來(lái)致力于為客戶提供成都做網(wǎng)站、成都網(wǎng)站建設(shè)、品牌網(wǎng)站制作、網(wǎng)絡(luò)營(yíng)銷推廣、搜索引擎SEO優(yōu)化等服務(wù)。經(jīng)過(guò)多年發(fā)展,公司擁有經(jīng)驗(yàn)豐富的技術(shù)團(tuán)隊(duì),先后服務(wù)、推廣了超過(guò)千家網(wǎng)站,包括各類中小企業(yè)、企事單位、高校等機(jī)構(gòu)單位。
cra2.0時(shí)代如何啟用裝飾器語(yǔ)法呢? 我們依舊采用的是react-app-rewired, 通過(guò)劫持webpack cofig對(duì)象, 達(dá)到修改的目的.
yarn add react-app-rewired
修改package.json
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }
安裝裝飾器語(yǔ)法所需的babel插件, 也可以順帶升級(jí)babel-core
yarn add @babel/plugin-proposal-decorators metro-react-native-babel-preset -D
在項(xiàng)目根目錄下創(chuàng)建.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對(duì)象, 對(duì)其babel規(guī)則進(jìn)行簡(jiǎn)單的修改.
附上完整的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" } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。