create-react-app创建项目并对cra兼webpack二次配置详解

使用react脚手架create-react-app创建项目

可全局安装react脚手架但不推荐(版本会时有更新)
推荐使用npx安装

//全局安装create-react-app创建项目
yarn global add create-react-app
create-react-app my-app

//使用npx安装
npx create-react-app my-app

cd my-app
npm start

react项目此时就已经创建在工作目录下

然后进入我们的react项目进行搭建环境的二次配置,我们的二次配置使用的是customize-cra
详情可参看github官方 https://github.com/arackaf/customize-cra

  • 安装customize-cra及原项目react-app-rewired
//支持webpack4+
yarn add customize-cra react-app-rewired -D

安装完成之后在项目根目录创建文件config-overrides.js来进行cra的二次配置

注意,所有的对webpack进行二次配置的内容必须添加在该文件内

举一个官网的例子

const {
  override,
  addDecoratorsLegacy,
  disableEsLint,
  addBundleVisualizer,
  addWebpackAlias,
  adjustWorkbox
} = require("customize-cra");
const path = require("path");

module.exports = override(
  // enable legacy decorators babel plugin
  addDecoratorsLegacy(),

  // disable eslint in webpack
  disableEsLint(),

  // add webpack bundle visualizer if BUNDLE_VISUALIZE flag is enabled
  process.env.BUNDLE_VISUALIZE == 1 && addBundleVisualizer(),

  // add an alias for "ag-grid-react" imports
  addWebpackAlias({
    ["ag-grid-react$"]: path.resolve(__dirname, "src/shared/agGridWrapper.js")
  }),

  // adjust the underlying workbox
  adjustWorkbox(wb =>
    Object.assign(wb, {
      skipWaiting: true,
      exclude: (wb.exclude || []).concat("index.html")
    })
  )
);
下边介绍几个常用的api

addDecoratorsLegacy()

  • 使项目支持使用装饰器,确保安装了@babel/plugin-proposal-decorators

disableEsLint()

  • 禁用eslint

useEslintRc(configFile)

  • 修改eslint默认代码规范

fixBabelImports(libraryName, options)

  • 使用babel-plugin-import来进行按需加载

addWebpackPlugin(plugin)

  • 向webpack的配置中添加plugin插件

enableEslintTypescript()

  • 升级eslint-loader在控制台输出js(x)或ts(x)的错误或警告

addWebpackAlias(alias)

  • 添加路径别名的设置

addLessLoader(loaderOptions)

  • 添加less文件的解析

addTslintLoader(loaderOptions)

  • 配置ts代码格式规范
更多api及详细使用可参考api文档**

https://github.com/arackaf/customize-cra/blob/master/api.md#addtslintloaderloaderoptions

经过一番配置,我们的react项目在抒写过程中那就是一帆风顺了
有需要的小伙伴赶快对自己的react项目进行配置吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.温m_

如果喜欢可以支持打赏小哥!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值