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了