之前发过一篇解决这个问题的文章,但是对create react app 都是有侵入的。
这里提出一个我觉得是最OK的解决方案,一波带走。关于Create React App不支持装饰器的解决方案
找到node_modules/react-scripts/config/webpack.config.dev.js文件。
观察其JSX|JS的loader配置。// Process JS with Babel.{ test: /\.(js|jsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { // @remove-on-eject-begin babelrc: false, presets: [require.resolve('babel-preset-react-app')], <===== 注意这里!! // @remove-on-eject-end // 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, },},复制代码
OK! 我们找到node_modules/babel-preset-react-app/index.js,然后加入装饰器支持。
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */'use strict';const plugins = [ // 增加装饰器的支持 require.resolve('babel-plugin-transform-decorators-legacy'), <=== 注意这里! // class { handleClick = () => { } } require.resolve('babel-plugin-transform-class-properties') ....复制代码
记着在对应的package.json下边加入babel-plugin-transform-decorators-legacy。
然后 cnpm install 再试试使用装饰器,你会发现OK啦。这是目前侵入最小的解决方案。