使用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项目进行配置吧