React创建项目

262 阅读2分钟

创建react项目

本地安装node什么的不赘述了。
之前本地全局安装过create-react-app,但是因为版本比较低,使用npx create-react-app my-app命令去创建新的项目时,会提示create-react-app不在继续支持之类的信息,官方提示的信息是使用npm uninstall -g create-react-app先删除老版本的,然后重新全局安装最新版本npm install -g create-react-app。 使用npx create-react-app my-app创建新项目。进入项目目录,使用命令npm start即可启动目录。用编译器打开项目,看到package.json里面

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

创建好新的项目之后,引入react-routerredux

npm install --save react-router-dom react-redux
npm install --save-dev redux-devtools

ant-design安装

npm install antd-mobile --save

ant-design的组件引用

import { Button } from 'antd-mobile';
ReactDOM.render(<Button>Start</Button>, mountNode);

样式引入

import 'antd-mobile/dist/antd-mobile.css';  // or 'antd-mobile/dist/antd-mobile.less'

从ant-design官网的文档来看,目前按需加载有两种方式

  • 使用babel-plugin-import
npm install babel-plugin-import --save-dev
// .babelrc or babel-loader option
{
  "plugins": [
    ["import", { libraryName: "antd-mobile", style: "css" }] // `style: true` 会加载 less 文件
  ]
}

然后只需从 antd-mobile 引入模块即可,无需单独引入样式。

// babel-plugin-import 会帮助你加载 JS 和 CSS
import { DatePicker } from 'antd-mobile';
  • 手动引入
import DatePicker from 'antd-mobile/lib/date-picker';  // 加载 JS
import 'antd-mobile/lib/date-picker/style/css';        // 加载 CSS
// import 'antd-mobile/lib/date-picker/style';         // 加载 LESS

明显手动引入很复杂。 到此处,创建react项目的基本操作都完成了,但是要想更灵活的配置项目的话,可能需要跑一下npm run eject来自己修改配置文件。

antd-mobile的文档里面提供了另外一种修改配置文件的方式

npm install react-app-rewired customize-cra --save-dev
/* package.json */
"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test --env=jsdom",
+   "test": "react-app-rewired test --env=jsdom",
}

react-app-rewired工具可以在不 'eject' 也不创建额外 react-scripts 的情况下修改 create-react-app 内置的 webpack 配置,然后你将拥有 create-react-app 的一切特性,且可以根据你的需要去配置 webpack 的 plugins, loaders 等。 安装 babel-plugin-import,不过配置的文件不一样了。

npm install babel-plugin-import --save-dev

然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。

const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true, // change importing css to less
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: { '@primary-color': '#1DA57A' },
  })
);

更改引用方式

import { Button } from 'antd-mobile';

使用less

npm install less less-loader --save

或者sass

npm install node-sass --save

将APP.css修改成对应的文件类型即可

添加调用接口的工具axios

npm install axios --save