使用customize-cra,react-app-rewired擴展create-react-app

先安裝相關依賴

經過 npm i customize-cra react-app-rewired -D 或者 yarn add customize-cra react-app-rewired --devjavascript

packages.json 同級目錄下建立 config-overrides.js 文件,以後就能夠在該文件中擴展相關配置了java

customize-cra 提供的插件react

經常使用配置

  • 使cra支持裝飾器來使用 Mobx

    yarn add @babel/plugin-proposal-decorators --devwebpack

    並在 package.json 同級目錄添加 .babelrcgit

    {
      "presets": ["react-app"],
      "plugins": [
        [
          "@babel/plugin-proposal-decorators",
          {
            "legacy": true
          }
        ]
      ]
    }

    而後在 config-overrides.js 添加:github

    const { override, addDecoratorsLegacy, useBabelRc } = require('customize-cra');
    
    module.exports = override(
      addDecoratorsLegacy(),
      useBabelRc()
    )

    就能夠在項目裏使用裝飾器了web

  • 添加 webpack alias

    修改 config-overrides.jsnpm

    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-loaderjson

    修改 config-overrides.js:api

    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')} ] ':msg:' ${chalk.bold('(:percent)')}`,
          clear: true
        })
      )
    )

    就能夠在 yarn build 時候看到進度條了

相關文章
相關標籤/搜索