背景
使用腳手架(vite)創(chuàng)建 React + TypeScript 項(xiàng)目
Ref:Vite - Scaffolding Your First Vite Project
前置條件:
- Node.js:v14.16.1
- yarn:1.22.10
示例代碼:github: test-vite
1. 初始化
(1)vite 腳手架
選取 react-ts
模板,
$ yarn create @vitejs/app test-vite --template react-ts
會(huì)創(chuàng)建這些文件,
test-vite
├── index.html
├── package.json
├── src
| ├── App.css
| ├── App.tsx
| ├── favicon.svg
| ├── index.css
| ├── logo.svg
| └── main.tsx
├── tsconfig.json
├── vite.config.ts
└── yarn.lock
(2)安裝依賴 & 運(yùn)行
$ cd test-vite
$ yarn
$ yarn dev
2. 使用 Ant Design
(1)添加必要的依賴
組件庫(kù) antd,CSS 預(yù)處理器 less
$ yarn add antd
$ yarn add -D less
(2)修改 vite 配置:vite.config.ts
配置 webpack 格式的 less 導(dǎo)入方式,并配置 less-loader。
- vite.config.ts
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [reactRefresh()],
/**
* [plugin:vite:css] '~antd/dist/antd.less' wasn't found.
* less import no support webpack alias '~'
*
* Ref: https://github.com/vitejs/vite/issues/2185#issuecomment-784637827
*/
resolve: {
alias: [
{ find: /^~/, replacement: '' }
],
},
/**
* [plugin:vite:css] Inline JavaScript is not enabled. Is it set in your options?
*
* Ref:
* https://blog.csdn.net/baobao_123456789/article/details/113986961
* https://stackoverflow.com/questions/46729091/enable-inline-javascript-in-less
*/
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
}
},
},
})
添加了兩個(gè)選項(xiàng):
-
resolve.alias
:為了兼容 webpack 導(dǎo)入 less 的寫法,以 "~" 開頭(@import '~...';) -
css.preprocessorOptions.less.javascriptEnabled
:這是 less-loader 的配置,啟用 Inline JavaScript
(3)全局引用 antd 樣式:重命名 src/index.css 為 src/index.less、修改 src/main.tsx
antd 的樣式需要單獨(dú)引入
- src/index.less
@import '~antd/dist/antd.less';
- src/main.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './index.less'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)
(4)添加示例代碼:添加 src/App.module.less、修改 src/App.tsx
vite 默認(rèn)支持 css modules
- src/App.module.less
.app {
background-color: gray;
}
- src/App.tsx
import React from 'react'
import {Row,Col} from 'antd'
import classes from './App.module.less'
function App() {
return (
<div className={classes.app}>
<Row>
<Col span="24">24</Col>
</Row>
<Row>
<Col span="12">12</Col>
<Col span="12">12</Col>
</Row>
<Row>
<Col span="8">8</Col>
<Col span="8">8</Col>
<Col span="8">8</Col>
</Row>
<Row>
<Col span="6">6</Col>
<Col span="6">6</Col>
<Col span="6">6</Col>
<Col span="6">6</Col>
</Row>
</div>
)
}
export default App
參考
github: test-vite
Vite: Scaffolding Your First Vite Project
Ant Design
Less.js
less-loader
css modules