react如果沒有經過配置,直接使用decorators裝飾器語法會報錯:
Support for the experimental syntax ‘decorators’ isn’t currently enabled
因為react默認是不支持裝飾器語法,需要做一些配置來啟用裝飾器語法。
step1:
在 tsconfig.json 中啟用編譯器選項 “experimentalDecorators”: true
vscode點擊設置,輸入搜索experimentalDecorators
step2:
安裝支持修飾器所需依賴。
yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env
創建.babelrc文件,配置
{"presets": ["@babel/preset-env"],"plugins": [["@babel/plugin-proposal-decorators",{"legacy": true}]]
}
step3:
安裝依賴
yarn add -D customize-cra react-app-rewired
在項目根目錄下創建 config-overrides.js 并寫入以下內容,覆蓋默認配置。
const path = require('path')
const { override, addDecoratorsLegacy } = require('customize-cra')function resolve(dir) {return path.join(__dirname, dir)
}const customize = () => (config, env) => {config.resolve.alias['@'] = resolve('src')if (env === 'production') {config.externals = {'react': 'React','react-dom': 'ReactDOM'}}return config
};
module.exports = override(addDecoratorsLegacy(), customize())
step4:
修改package.json文件中 scripts 腳本。
"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build","test": "react-app-rewired test","eject": "react-scripts eject"}
上面4個步驟配置完成后,如果mobx修飾器還是不起作用,就可能是mobx版本有問題,執行step5。
step5:
執行下面命令
yarn add -D mobx@5 mobx-react@5
執行到step5,就能成功使用mobx修飾器了。
注意,如果報錯
Parsing error: Cannot use the decorators and decorators-legacy plugin together
可以創建.eslintrc.js文件,配置即可解決eslint報錯問題
parserOptions: {parser: 'babel-eslint',ecmaFeatures: {// 支持裝飾器legacyDecorators: true,},},