React使用react-app-rewired和customize-cra修改webpack的基本配置

酆阳煦
2023-12-01

使用 react-app-rewiredcustomize-crawebpack进行配置定义

主要是用的插件react-app-rewired customize-cra

  1. 安装yarn add react-app-rewired customize-cra -D

  2. 首先先在package.json中配置 把react-scripts替换成为react-app-rewired

    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    }
    

    替换成为

    "scripts": {
        "start": "react-app-rewired start",
        "build": "react-app-rewired build",
        "test": "react-app-rewired test",
        "eject": "react-scripts eject"
    }
    
  3. 在项目根目录和package.json同级下面新建一个 config-overrides.js的文件

    const { override } = require('customize-cra')
    const path = require('path')
    module.exports = {
      webpack: override(
      // 设置配置代码
      )
    }
    

1.React使用@操作符代表 src 目录-从customize-cra导入addWebpackAlias

const {
  ...
  addWebpackAlias,
  ...
} = require('customize-cra')
module.exports = {
  webpack: override(
    ...
  	// 配置 @
    addWebpackAlias({
      '@': path.resolve(__dirname, 'src')
    })
    ...
  )
}

2. 按需引入-从customize-cra导入fixBabelImports

const {
  ...
  fixBabelImports,
  ...
} = require('customize-cra')
module.exports = {
  webpack: override(
    ...
  	// 配置antd 按需引入
    fixBabelImports('import', {
      libraryName: 'antd',
      libraryDirectory: 'es',
      style: 'css'
    }),
    ...
  )
}

3. 导入文件的时候可以不用添加文件的后缀名-从customize-cra导入addWebpackResolve

例子 import Personal from './components/Personal.tsx' —> import Personal from './components/Personal'

const {
  ...
  addWebpackResolve,
  ...
} = require('customize-cra')
module.exports = {
  webpack: override(
    ...
  	// 导入文件的时候可以不用添加文件的后缀名
    addWebpackResolve({
      extensions: ['.tsx', '.ts', '.js', '.jsx', '.json']
    }),
    ...
  )
}

4.添加代理处理跨域

const {
  ...
  override,
  overrideDevServer,
  ...
} = require('customize-cra')
module.exports = {
  webpack: override(),
  处理跨域
  devServer: overrideDevServer(config => {
    config.proxy = {
      '/proxy/': {
        target: 'http://127.0.0.1:7001/v1',
        changeOrigin: true,
        pathRewrite: { '^/proxy': '/' }
      }
    }
    return config
  })
}
 类似资料: