更多内容,请查看博客原文:搭建reactjs和antd的原始项目
https://finolo.gy/2020/01/搭建reactjs和antd的原始项目/
安装node, npm
查看安装的版本信息
node -v
v10.16.0
npm -v
6.10.0
安装react脚手架工具
npm install -g create-react-app
查看安装版本
create-react-app -V
3.3.0
新建一个项目
create-react-app my-app
启动项目
cd my-app
yarn start
安装react-router-dom
react-router 4.0版本以后,就只需要安装react-router-dom
了,dom代表有dom元素在里面。
yarn add react-router-dom
安装less-loader, less
如果写一个.less
的样式文件,react脚手架工具创建出来的项目默认是不支持的,所以需要安装less-loader
模块。
yarn add less-loader less
安装好less-loader后,需要做一些配置才能生效。
执行yarn eject
,把配置文件把暴露出来。系统可能会提示让把package.json
和yarn.lock
commit掉。
可以看到工程中多出了scripts
和config
目录
编译config/webpack.config.js
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
// 添加如下内容
{
test: /\.less$/,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader', // translates CSS into CommonJS
}, {
loader: 'less-loader', // compiles Less to CSS
options: {
sourceMap: true,
modifyVars: {
// '@primary-color': '#F0CF13',
},
javascriptEnabled: true,
}
}]
},
// 添加上面内容
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
}
...
]
@primary-color可以不用设置。
因为修改了配置,所以需要重启项目。
这时我们发现,less的样式已经生效了。
安装axios
yarn add axios
安装antd
yarn add antd
在使用时,引入css文件。如果要使用Button组件,引入即可。
import 'antd/dist/antd.css'
import {Button} from "antd";
antd是用less来写的,我们加载的antd.css是全部的样式,这样加载的内容太多了。
我们如果要达到按需加载的目的,还得安装babel-plugin-import
yarn add babel-plugin-import
安装好以后,在package.json
里面的babel
属性里面添加如下内容:
"babel": {
"presets": [
"react-app"
],
// 添加下面的内容
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": true
}
]
]
// 添加上面的内容
}
重启项目,我们发现,当我们注释掉css以后,antd的样式还是可以正常输出。
// import 'antd/dist/antd.css'
import {Button} from "antd";
更多内容,请查看博客原文:搭建reactjs和antd的原始项目
https://finolo.gy/2020/01/搭建reactjs和antd的原始项目/