ReactJS初探(一)

前端项目打算使用ReactJS+Webpack+ant-design来做。
ReactJS的官网:https://reactjs.org/docs/try-react.html
Webpack的入门文章:https://www.jianshu.com/p/42e11515c10f
ant-design的GitHub地址:https://github.com/ant-design/ant-design

Hello World

当前使用的react版本:16.2.0,内部自带Babel和Webpack,无需自己配置。新建和使用方法:

npm install -g create-react-app
create-react-app my-app
cd my-app
npm start

安装ant-design

安装:

npm install antd --save

使用:

//替换index.js
import 'antd/dist/antd.css';  // or 'antd/dist/antd.less'
import { DatePicker } from 'antd';
ReactDOM.render(, mountNode);

npm start运行后会看到:

image.png

这是因为把antd整个包都使用了,然而你真正用的只有DatePicker,可以使用babel-plugin-import来按需加载,减小bundle的大小。
因此我们可以这样改:

import Button from 'antd/lib/button';
import 'antd/lib/button/style'; // or antd/lib/button/style/css for css format file

也可以使用babel-plugin-import

import { Button } from 'antd';

可以看到使用babel-plugin-import可以减轻代码量,美观代码。
babel-plugin-import的配置方式:https://github.com/ant-design/babel-plugin-import

这种配置方式并不适应与新的react,“babel-plugin-import will not work properly if you add the library to the webpack config vendor."

配置webpack

webpack.config.dev.jswebpack.config.prod.js中搜索// Process JS with Babel.,修改如下:

options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
             //配置babel-plugin-import
              plugins: [["import", { libraryName: "antd", style: "css" }]],
              // @remove-on-eject-end
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            },

重新npm start即可。

你可能感兴趣的:(ReactJS初探(一))