14

使用create-react-app 搭建react + ts + antd框架

 3 years ago
source link: http://www.cnblogs.com/littleSpill/p/14015803.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、创建项目

 使用npx create-react-app (项目名) --template typescript  创建项目

①如果App.tsx文件有如下报错: (没有报错的请忽略)

6ZVVbuF.png!mobile

需要将tsconfig.json文件里的 "jsx": "react-jsx" 配置改为 "jsx": "react" 即可。

bAzUVzi.png!mobile

② 此时运行yarn start会报错

3yQBziM.png!mobile

此时需要将react-scripts版本4.0.0降级为3.4.4  (参考: https://stackoverflow.com/questions/64593336/typeerror-cannot-assign-to-read-only-property-paths-of-object-for-compileropt

③ 如遇到报错 :  TypeScript 引入第三方包,报无法找到模块错误 (参考: https://www.cnblogs.com/xym4869/p/13323483.html )

二、安装ant-design 并配置自定义主题、按需加载(参考antd官网)、绝对路径的引用

yarn add antd @craco/craco craco-less
yarn add @babel/plugin-proposal-decorators babel-plugin-import --dev

①修改  package.json 里的  scripts 属性:

"scripts": {
    "start": "set PORT=3000 && craco start",
    "build": "set GENERATE_SOURCEMAP=false && craco build",
    "test": "craco test"
  },

② 在项目根目录创建一个  craco.config.js 用于修改默认配置 (参考: https://blog.csdn.net/qq_39223195/article/details/106287522

const CracoLessPlugin = require('craco-less');
const path = require('path')

const pathResolve = pathUrl => path.join(__dirname, pathUrl)

module.exports = {
    webpack: {
        alias: {
            '@@': pathResolve('.'),
            '@': pathResolve('src'),
            '@common': pathResolve('src/common'),
            '@config': pathResolve('src/config'),
            '@components': pathResolve('src/components'),
        }
    },
    babel: {
        plugins: [
            ['import', { libraryName: 'antd', style: true }],
            ['@babel/plugin-proposal-decorators', { legacy: true }]
        ]
    },
    plugins: [
        {
            plugin: CracoLessPlugin,
            options: {
                lessLoaderOptions: {
                    lessOptions: {
                        modifyVars: { '@primary-color': 'red' },
                        javascriptEnabled: true,
                    },
                },
            },
        },
    ],
};

③在根目录创建 paths.json 文件

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
          "@@/*": ["./*"],
          "@/*": ["src/*"],
          "@common/*": ["src/common/*"],
          "@config/*": ["src/config/*"],
          "@components/*": ["src/components/*"]
        }
    }
  }

④修改tsconfig.json配置,添加上以下内容。将paths.json文件引入。直接在tsconfig.json文件里写会报错。 这样配置完之后引入文件的时候可以@/xxx/xxx并且会有提示。

"extends": "./paths.json",

⑤ 将App.css和index.css改为App.less和index.less

⑥ demo

Vv2UNnb.png!mobile

三、代码规范(eslint)的配置 (参考: https://www.npmjs.com/package/eslint )

./node_modules/.bin/eslint --init

如果是windows系统需要将‘/’换成 ‘ \ ’,  然后按照自己的需求来选择配置即可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK