首頁  >  文章  >  web前端  >  react 裝飾器報錯怎麼辦

react 裝飾器報錯怎麼辦

藏色散人
藏色散人原創
2023-01-05 11:50:213192瀏覽

react裝飾器報錯的解決方法:1、透過「create-react-app mobx-study」建立專案;2、透過「yarn add -D react-app-rewired customize-cra」安裝外掛; 3.修改package.json檔案中scripts腳本;4、在專案根目錄下創建「config-overrides.js」和「.babelrc」即可。

react 裝飾器報錯怎麼辦

本教學操作環境:Windows10系統、react18.0.0版、Dell G3電腦

react 裝飾器報錯怎麼辦?

React的decorators裝飾器報錯



react 裝飾器報錯怎麼辦

一、decorators裝飾器報錯@

在初次使用React 的裝飾器時,第一次在專案中使用@

會報錯,原因是react預設是不支援裝飾器的,所以才會報錯,所以是需要做一些配置來支援裝飾器。

【錯誤顯示:Parsing error: This experimental syntax requires enabling one of the following parser plugin(s): “decorators-legacy”, “decorators”.】

1. 建立專案

npm install -g create-react-app  
// 安装create-react-app,已安装请忽略
create-react-app mobx-study


2. 安裝外掛程式- 改變create-react-app 中webpack 設定react 裝飾器報錯怎麼辦

yarn add -D react-app-rewired customize-cra 
yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env
3.修改package.json檔案中scripts 腳本
// package.json
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }
4. 在專案根目錄下建立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())

5. 在專案根目錄下建立.babelrc 並寫入以下內容

{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ]
    ]}
基本上完成以上步驟就可以正常使用裝飾器了,再也不會報@ 的錯誤了。同時Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled這個錯誤也將消失。

############二、對修飾器的實驗支援功能可能會在未來的版本中更改。在 “tsconfig” 或 “jsconfig” 中設定 “experimentalDecorators” 選項以刪除此警告。 ts(1219)#########設定=> 搜尋experimentalDecorators => 打上勾勾############################################################ ########推薦學習:《###react影片教學###》##########

以上是react 裝飾器報錯怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn