该园用来记录个人的学习内容,有些杂乱,谅解~嘿嘿~

Chloe

自学前端的小菜鸟一枚呀~
记录学习的知识

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

posted @ 2022-04-11 10:42  Chloe56  阅读(811)  评论(3编辑  收藏  举报