此项目运用 TypeScript + cra
安装 ts 版 cra
| 1
 | $ yarn create react-app 项目名 --template typescript
 | 
引入 antd
修改 src/App.tsx,引入 antd 按钮组件
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | import React, { FC } from "react";import { Button } from "antd";
 import "./App.css";
 
 const App: FC = () => (
 <div className="App">
 <Button type="primary">Button</Button>
 </div>
 );
 
 export default App;
 
 | 
修改 index.css 在文件顶部引入 antd 样式
| 1
 | @import "~antd/dist/antd.css";
 | 
安装 craco 和 craco-less
| 12
 
 | $ yarn add @craco/craco$ yarn add craco-less
 
 | 
在 package.json 中修改 script 属性
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | "scripts": {
 -   "start": "react-scripts start",
 -   "build": "react-scripts build",
 -   "test": "react-scripts test",
 +   "start": "craco start",
 +   "build": "craco build",
 +   "test": "craco test",
 }
 
 | 
在项目跟目录创建 craco.config.js 用于修改默认配置
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 
 | const CracoLessPlugin = require("craco-less");
 
 module.exports = {
 plugins: [
 {
 plugin: CracoLessPlugin,
 options: {
 lessLoaderOptions: {
 lessOptions: {
 modifyVars: { "@primary-color": "#1DA57A" },
 javascriptEnabled: true,
 },
 },
 cssLoaderOptions: {
 modules: { localIdentName: "[local]_[hash:base64:5]" },
 },
 },
 },
 ],
 };
 
 | 
创建声明文件
用于声明.less 结尾的文件,在 src 目录下创建 type-css.d.ts
| 12
 3
 4
 5
 6
 
 | declare module "*.less" {const classes: {
 readonly [key: string]: string;
 };
 export default classes;
 }
 
 | 
创建完后要引入,在 tsconfig.json 中
| 12
 3
 4
 5
 6
 
 | "compilerOptions": {+  "experimentalDecorators": true,  // 新增
 },
 "include": [
 +  "type-css.d.ts"
 ]
 
 | 
测试
新建一个 test.less 文件
| 12
 3
 4
 5
 
 | .box {width: 100px;
 height: 100px;
 background: pink;
 }
 
 | 
在 App.tsx 中引入
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | import React, { FC } from "react";import { Button } from "antd";
 import styles from "./test.less";
 
 const App: FC = () => (
 <div className="App">
 <Button type="primary">Button</Button>
 <p className={styles.box}></p> {/* 局部样式用xx.xx来写 */}
 </div>
 );
 
 export default App;
 
 |