初始化
创建
yarn create vite
执行步骤
√ Project name: 项目名称
√ Select a framework: » React
√ Select a variant: » TypeScript
安装依赖
yarn
ts
Typescript 发布5.0以后,默认模块的解析策略是bundler,是一种兼容妥协方案;
VsCode 最新版本的软件是支持的;
tsconfig.json 文件添加配置项
"compilerOptions": {
"moduleResolution": "Bundler", // 可修改成 node 解析 或升级 Vscode
"allowImportingTsExtensions": true, // 允许默认导出
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
},
vite.config
Node.js API 的静态类型声明
yarn add @types/node -D
配置项
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path' // TS解析 yarn add @types/node -D
export default defineConfig({
// root: './', // 入口文件,默认 ./ 即 index.html
// base: '/api', // 基础路径 http://localhost:5173/api
// publicDir:'public' // 静态资源设置目的,默认路径 public,可直接访问 http://localhost:5173/vite.svg
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
server: {
// host: 'localhost', // 必须合法主机 127.0.0.1 或 localhost
port: 8080, // 设置端口
proxy: {
'/api': 'http://'
}
},
plugins: [react()]
})
环境变量
根目录创建 .env.development
# 开发环境
NODE_ENV=development
# 接口API地址
VITE_BASE_API = /api
根目录创建 .env.production
# 生产环境
NODE_ENV=production
# 接口API地址
VITE_BASE_API = /api
根目录创建 .env.stag
# 测试环境
NODE_ENV=production
# 接口API地址
VITE_BASE_API = /api
package.json
"scripts": {
"dev": "vite",
"build:stg": "tsc && vite build --mode stag", // 指定 .env.stag
"build": "tsc && vite build",
"lint": "eslint .",
"preview": "vite preview"
}
行时环境
index.html
<html lang="en" data-env="stg">
src > 创建 config.ts
const env = (document.documentElement.dataset.env as ENV) || 'stg'
// 类似 env,运行时环境配置
const config = {
// 开发环境
dev: {
baseApi: '/api',
},
// 测试环境
stg: {
baseApi: '/api',
},
// 生产环境
prd: {
baseApi: '/api',
}
}
export default {
env,
...config[env]
}
editor
根目录创建 .editorconfig 文件
# https://editorconfig.org
root = true # 根文件,所有文件生效
[*]
charset = utf-8 # 编辑器格式
indent_style = tab # 缩进符
indent_size = 2 # 缩进距离
# 不同操作系统换行符不同
end_of_line = lf # 换行符 (lf | cr | crlf (大小写不限))
insert_final_newline = true # 代码最后新增一行
trim_trailing_whitespace = true # 修剪尾随空格
prettier
--exact 指示使用精确的版本号进行安装
yarn add --dev --exact prettier
根目录创建配置 .prettierrc.cjs
module.exports = {
printWidth: 120, // 每行最大列,超过换行
useTabs: false, // 使用制表符而不是空格缩进
tabWidth: 2, // 缩进
semi: false, // 是否添加分号
singleQuote: true, // :是否单引号
jsxSingleQuote: true, // 在 JSX 中是否使用单引号
arrowParens: 'avoid', // 箭头函数如果是一个参数的时候,去掉括号
bracketSpacing: true, // 对象、数组括号与文字间添加空格
trailingComma: 'none', // 尾随逗号
endOfLine: 'auto' // 与 .editorconfig 保持一致设置
}
根目录创建配置 .prettierignore 文件
node_modules/**
dist/**
public/**
doc/**
*.md
coverage/**
.settings.json
source.fixAll 通过 eslint --fix 能自动修复,如定义 var a = 3 ,自动修复为 const a = 3 ;
{
// 保存的时候自动格式化
"editor.formatOnSave": true,
// 开启 stylelint 自动修复
"editor.codeActionsOnSave": {
"source.fixAll": true
},
// 默认格式化工具选择prettier
// "editor.defaultFormatter": "esbenp.prettier-vscode"
}