React項目中decorators裝飾器報錯


問題:
我先安裝了decorators:

然后運行項目就報錯emmmmm:

src\pages\home\cookbook\swiper.jsx
Line 21: Parsing error: This experimental syntax requires enabling one of the following parser plugin(s): "decorators-legacy", "decorators". (21:0)


下面是百度之后轉載的文章:

在初次使用React 的裝飾器時,第一次在項目中使用 @會報錯,原因是react默認是不支持裝飾器的,所以才會報錯,所以是需要做一些配置來支持裝飾器。

  1. 創建項目
npm install -g create-react-app  // 安裝create-react-app,已安裝請忽略
create-react-app mobx-study
  1. 安裝插件 —— 改變 create-react-app 中 webpack 配置
yarn add -D react-app-rewired customize-cra 
yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env
  1. 修改package.json文件中 scripts 腳本
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }
  1. 在項目根目錄下創建 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())
  1. 在項目根目錄下創建 .babelrc 並寫入以下內容
{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ]
    ]
}

基本完成以上步驟就可以正常使用裝飾器了,再也不會報 @ 的錯誤了。同時Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled這個錯誤也將消失。

版權聲明:本文為CSDN博主「程序燕」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/lfy_wybss/article/details/122079178


雖然我用了以上方法,但是它emmmm。。。好吧還是在報錯,但是關掉報錯並不耽誤使用,有人懂為什么嗎,哭了555555555


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM