如何在react中使用decorator

2020-03-27
如何在react中使用decorator

decorator目前都需要修改babel才能使用

说一下具体的操作方法 踩了一天的坑。。。

步骤1: yarn create react-app myapp
习惯用yarn npm也行 都一样
 
步骤2: yarn add @babel/plugin-proposal-decorators -D
装依赖!!!
 
步骤3: yarn eject 或者 修改node_modules
先说yarn eject, 将配置文件暴露到项目中
执行完成之后,修改package.json中的babel 修改如下
 
"babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      ]
    ]
  },
 
但是,react的默认配置看的人头晕,如果不想eject
修改 node_modules -> react-scripts -> config -> webpack.config.js
找到 test: /.(js|mjs|jsx|ts|tsx)$/ 在下面的plugins中加入新的配置 如下红色部分
 
{
              test: /.(js|mjs|jsx|ts|tsx)$/,
              include: paths.appSrc,
              loader: require.resolve('babel-loader'),
              options: {
                customize: require.resolve(
                  'babel-preset-react-app/webpack-overrides'
                ),
                babelrc: false,
                configFile: false,
                presets: [require.resolve('babel-preset-react-app')],
                cacheIdentifier: getCacheIdentifier(
                  isEnvProduction
                    ? 'production'
                    : isEnvDevelopment && 'development',
                  [
                    'babel-plugin-named-asset-import',
                    'babel-preset-react-app',
                    'react-dev-utils',
                    'react-scripts',
                  ]
                ),
                // @remove-on-eject-end
                plugins: [
                  [
                    require.resolve('babel-plugin-named-asset-import'),
                    {
                      loaderMap: {
                        svg: {
                          ReactComponent:
                            '@svgr/webpack?-svgo,+titleProp,+ref![path]',
                        },
                      },
                    },
                  ],
                  [
                    "@babel/plugin-proposal-decorators",
                    {
                      "legacy": true
                    }
                  ]
                ],
                // This is a feature of `babel-loader` for webpack (not Babel itself).
                // It enables caching results in ./node_modules/.cache/babel-loader/
                // directory for faster rebuilds.
                cacheDirectory: true,
                // See #6846 for context on why cacheCompression is disabled
                cacheCompression: false,
                compact: isEnvProduction,
              },
            },

大功告成,可以愉快的用decorator了
原文地址:https://www.cnblogs.com/lanpang9661/p/12582554.html