React项目中decorators装饰器报错问题解决方案

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React项目中decorators装饰器报错问题解决方案

Chloe56   2023-02-03 我要评论

问题:

我先安装了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

2.安装插件 —— 改变 create-react-app 中 webpack 配置

yarn add -D react-app-rewired customize-cra 
yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env

3.修改package.json文件中 scripts 脚本

"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())

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这个错误也将消失。

虽然我用了以上方法,但是它emmmm。。。好吧还是在报错,但是关掉报错并不耽误使用,有人懂为什么吗,哭了555555555

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们