react安装最好使用 yarn 来安装插件,因为大部分使用npm时会出现各种错误
npm install yarn -g
切换并使用淘宝镜像:
yarn config set registry=https://registry.npm.taobao.org -g
在react版本16.8之前:
yarn add react-app-rewired@2.1.6 customize-cra@1.0.0 babel-plugin-import@1.13.1 less@3.12.2 less-loader@7.1.0
并修改package.json文件
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
在根目录下创建config-overrides.js
//配置具体的修改规则
const { override, fixBabelImports,addLessLoader} = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
addLessLoader({
lessOptions:{
javascriptEnabled: true,
modifyVars: { '@primary-color': 'green' },
}
}),
);
备注:不用在组件里亲自引入样式了, 即: import 'antd/dist/antd.min.css'应该删除
在React18版本后引入antd配合craco来设置
安装 @craco/craco 跟 babel-plugin-import
yarn add @craco/craco babel-plugin-import
将package.json文件修改为
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
此时在安装craco-less,并在根目录创建 craco.config.js文件
/*
注意:这边一定需要加上一个 --force, 否则会出现一个在 node_modules中会出现一个error
错误是: 在tsconfig-paths中有个文件没有引入的错误, 使用npm i craco-less --force
就没有以下问题
*/
npm i craco-less --force
const CracoLessPlugin = require("craco-less");
// 需要安装两个插件:`yarn add craco-less` `yarn add babel-plugin-import` 从而实现样式的按需引入
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { "@primary-color": "#1DA57A" },
javascriptEnabled: true,
},
},
},
},
],
babel: {
//支持装饰器
plugins: [
[
"import",
{
libraryName: "antd",
libraryDirectory: "es",
style: true, //设置为true即是less 这里用的是css,如果是scss,则需要设置为false,否则不能正常生效
},
],
],
},
};
后面 npm start 或 yarn start
附上我的package.json文件
{
"name": "react-admin_client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@craco/craco": "^6.4.4",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"antd": "^4.21.5",
"babel-plugin-import": "^1.13.5",
"craco-less": "^2.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}