使用customize-cra,react-app-rewired扩展create-react-app
先安装相关依赖
通过 npm i customize-cra react-app-rewired -D
或者 yarn add customize-cra react-app-rewired --dev
在 packages.json
同级目录下创建 config-overrides.js
文件,之后就可以在该文件中扩展相关配置了
customize-cra 提供的插件
配置package.json
将script
里面的start,build脚本改为
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
...
}
常用配置
-
使cra支持装饰器来使用
Mobx
:yarn add @babel/plugin-proposal-decorators --dev
并在
package.json
同级目录添加.babelrc
:{ "presets": ["react-app"], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ] }
然后在
config-overrides.js
添加:const { override, addDecoratorsLegacy, useBabelRc } = require('customize-cra'); module.exports = override( addDecoratorsLegacy(), useBabelRc() )
就可以在项目里使用装饰器了
-
添加
webpack alias
修改
config-overrides.js
:const { override, addWebpackAlias } = require('customize-cra'); const path = require('path'); module.exports = { addWebpackAlias({ '@': path.resolve(__dirname, 'src'), 'components': path.resolve(__dirname, 'src/components'); }) }
-
修改AntD主题色,并添加
Less
支持,关闭sourcemap:首先
yarn add less less-loader
修改
config-overrides.js
:const { override, fixBabelImports, addLessLoader } = require("customize-cra"); process.env.GENERATE_SOURCEMAP = "false"; module.exports = override( fixBabelImports("import", { libraryName: 'antd', libraryDirectory: "es", style: true, }), addLessLoader({ javascriptEnabled: true, modifyVars: { '@primary-color': '#1DA57A' }, }) );
-
添加webpack插件:
这里以添加build时的进度条插件举例:
首先
yarn add progress-bar-webpack-plugin chalk --dev
之后修改
config-overrides.js
const { override, ..., addWebpackPlugin } = require('customize-cra'); const ProgressBarPlugin = require('progress-bar-webpack-plugin'); const chalk = require('chalk'); module.exports = override( // 其他配置 ..., addWebpackPlugin(new ProgressBarPlugin({ complete: "█", format: `${chalk.green('Building')} [ ${chalk.green(':bar')} ] ${chalk.bold(':percent')}`, clear: true }) ) )
就可以在
yarn build
时候看到进度条了