在 TypeScript 中使用

    请确保电脑上已经安装了最新版的 或者 npm

    使用 yarn 创建 项目。

    如果你使用的是 npm(接下来我们都会用 yarn 作为例子,如果你习惯用 npm 也没问题)。

    1. $ npx create-react-app antd-demo-ts --typescript

    然后我们进入项目并启动。

    1. $ cd antd-demo-ts
    2. $ yarn start

    此时浏览器会访问 http://localhost:3000/ ,看到 Welcome to React 的界面就算成功了。

    1. $ yarn add antd

    修改 src/App.tsx,引入 antd 的按钮组件。

    修改 src/App.css 引入 antd 的样式。

    1. @import '~antd/dist/antd.css';
    2. .App {
    3. text-align: center;
    4. }
    5. ...

    重新启动 yarn start,现在你应该能看到页面上已经有了 antd 的蓝色按钮组件,接下来就可以继续选用其他组件开发应用了。其他开发流程你可以参考 create-react-app 的。

    此时我们需要对 create-react-app 的默认配置进行自定义,这里我们使用 react-app-rewired (一个对 create-react-app 进行自定义配置的社区解决方案)。

    引入 react-app-rewired 并修改 package.json 里的启动配置。由于新的 版本的关系,你还需要安装 customize-cra

    1. $ yarn add react-app-rewired customize-cra
    1. /* package.json */
    2. "scripts": {
    3. + "start": "react-app-rewired start",
    4. - "build": "react-scripts build",
    5. - "test": "react-scripts test",
    6. + "test": "react-app-rewired test",
    7. }

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

    是一个用于按需加载组件代码和样式的 babel 插件(原理),现在我们尝试安装它并修改 config-overrides.js 文件。

    1. $ yarn add babel-plugin-import
    1. + const { override, fixBabelImports } = require('customize-cra');
    2. - module.exports = function override(config, env) {
    3. - // do stuff with the webpack config...
    4. - return config;
    5. - };
    6. + module.exports = override(
    7. + fixBabelImports('import', {
    8. + libraryName: 'antd',
    9. + libraryDirectory: 'es',
    10. + style: 'css',
    11. + }),
    12. + );

    然后移除前面在 src/App.css 里全量添加的 @import '~antd/dist/antd.css'; 样式代码,并且按下面的格式引入模块。

    1. import React, { Component } from 'react';
    2. - import Button from 'antd/es/button';
    3. + import { Button } from 'antd';
    4. import './App.css';
    5. class App extends Component {
    6. render() {
    7. return (
    8. <div className="App">
    9. <Button type="primary">Button</Button>
    10. </div>
    11. );
    12. }
    13. }
    14. export default App;

    最后重启 yarn start 访问页面,antd 组件的 js 和 css 代码都会按需加载,你在控制台也不会看到这样的。关于按需加载的原理和其他方式可以阅读这里

    自定义主题

    按照 的要求,自定义主题需要用到 less 变量覆盖功能。我们可以引入 customize-cra 中提供的 less 相关的函数 addLessLoader 来帮助加载 less 样式,同时修改 config-overrides.js 文件如下。

    这里利用了 的 modifyVars 来进行主题配置,变量和其他配置方式可以参考 配置主题 文档。

    先按照 中的说明操作,再配置 TypeScript 开发环境。

    你也可以使用 react-scripts-ts-antd,其中包括了 ts-import-plugin,react-app-rewired,scss,less 等插件。你可以通过只运行一个命令来创建一个没有任何配置的新项目。