之前發過一篇解決這個問題的文章,但是對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啦。這是目前侵入最小的解決方案。