react启用mobx @decorators装饰器语法

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,
        },
      },

在这里插入图片描述

相关推荐

  1. ArkTs 语法学习 ---- 组件相关装饰

    2024-07-11 15:44:05       53 阅读
  2. 装饰 之accessor 装饰

    2024-07-11 15:44:05       50 阅读
  3. 装饰基础知识

    2024-07-11 15:44:05       57 阅读
  4. 装饰模式

    2024-07-11 15:44:05       53 阅读
  5. Python装饰

    2024-07-11 15:44:05       60 阅读
  6. 装饰设计模式

    2024-07-11 15:44:05       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 15:44:05       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 15:44:05       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 15:44:05       58 阅读
  4. Python语言-面向对象

    2024-07-11 15:44:05       69 阅读

热门阅读

  1. 学习小记-使用Redis的令牌桶算法实现分布式限流

    2024-07-11 15:44:05       22 阅读
  2. 梯度下降算法的原理

    2024-07-11 15:44:05       22 阅读
  3. pytorch的axis的理解

    2024-07-11 15:44:05       22 阅读
  4. 搭建基于 ChatGPT 的问答系统

    2024-07-11 15:44:05       22 阅读
  5. C语言 将两个字符串连接起来,不用strcat函数

    2024-07-11 15:44:05       19 阅读