Front End

[FE] Vite: React + TypeScript 项目

2021-04-19  本文已影响0人  何幻

背景

使用脚手架(vite)创建 React + TypeScript 项目
Ref:Vite - Scaffolding Your First Vite Project

前置条件:

示例代码:github: test-vite

1. 初始化

(1)vite 脚手架

选取 react-ts 模板,

$ yarn create @vitejs/app test-vite --template react-ts

会创建这些文件,

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)安装依赖 & 运行

$ cd test-vite
$ yarn
$ yarn dev

2. 使用 Ant Design

(1)添加必要的依赖

组件库 antd,CSS 预处理器 less

$ yarn add antd
$ yarn add -D less

(2)修改 vite 配置:vite.config.ts

配置 webpack 格式的 less 导入方式,并配置 less-loader

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,
      }
    },
  },
})

添加了两个选项:

(3)全局引用 antd 样式:重命名 src/index.css 为 src/index.less、修改 src/main.tsx

antd 的样式需要单独引入

@import '~antd/dist/antd.less';
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 默认支持 css modules

.app {
  background-color: gray;
}
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

上一篇 下一篇

猜你喜欢

热点阅读