共计 17740 个字符,预计需要花费 45 分钟才能阅读完成。
前言
vite 是个什么玩意哈😳?都 2021 年了,别说不晓得哈?要是不晓得小心 尤大大
不让你用 vue
了。
vite
是一个开发构建工具,开发过程中它利用浏览器 native ES Module
个性导入组织代码,生产中利用 rollup
作为打包工具,且尤 vue
作者 尤雨溪
组织团队开发,它有如下特点:
- 启动快
- 热模块更新
- 按需编译
- 完满兼容
rollup
生态
咱们的新我的项目曾经尝试用了一下 vite
, 成果的话,的确比webpack
好点,当初我来论述一下,怎么搭建一个 企业级
的vite
工程化。
根底筹备
- 新建文件夹
config
,public
,src
-
生成
package.json
,执行如下命令👇$ npm init
- 新增
index.html
,tsconfig.json
,vite.config.ts
,.gitignore
文件
我的项目根底构造如下:
├── config # 我的项目脚手架的配置文件 | |
├── public # 动态文件 | |
├── src # 源代码 | |
├── index.html # root | |
├── .gitignore # git 漠视文件 | |
├── vite.config.ts # 我的项目全局 vite 配置文件 | |
├── tsconfig.json # 我的项目全局 ts 配置文件 | |
└── package.json # package.json |
开始
装置必须依赖
开发
$ npm install vite typescript @vitejs/plugin-react-refresh -D
生产
$ npm install react react-dom -S
编写配置
在 src
文件夹下新建main.tsx
,App.tsx
,app.css
-
在
src/App.tsx
文件中书写如下代码import React, {FC, useEffect} from 'react'; import './app.css'; const App: FC = () => {useEffect(() => {console.log(`vite-react-cil`); }, []); return ( <div> <h2>Welcome to vite-react-cil</h2> </div> ); }; export default App; - 在
src/app.css
文件中书写如下代码
* { | |
padding: 0; | |
margin: 0; | |
} | |
.App{width:200px;} |
-
在
src/main.tsx
文件中书写如下代码import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'), ); -
在
tsconfig.json
文件中书写如下代码{ "compilerOptions": { "baseUrl": "./", "paths": {"@/*": ["src/*"] }, "types": ["vite/client"], "target": "ESNext", "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": false, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "ESNext", "moduleResolution": "Node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react" }, "include": ["./src"], "exclude": ["node_modules"] } -
在
config
文件夹中新建plugins
文件夹,该文件件专门用来解决vite
第三方插件,而后在config/plugins
文件夹中新建index.ts
文件,且在index.ts
文件中编写如下代码:import {Plugin} from 'vite'; import reactRefresh from '@vitejs/plugin-react-refresh'; export default function createVitePlugins() {const vitePlugins: (Plugin | Plugin[])[] = [reactRefresh(), ]; return vitePlugins; } -
在
vite.config.ts
文件中书写如下代码import {defineConfig} from 'vite'; import createVitePlugins from './config/plugins'; export default defineConfig((configEnv) => { return {plugins: createVitePlugins(), }; }); - 在
public
文件夹中寄存一个favicon.ico
图文件. -
在
index.html
文件中书写如下代码<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>vite-react-cil</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html> -
在
.gitignore
文件中书写如下配置node_modules .DS_Store dist coverage dist-ssr *.local -
在
package.json
文件中增加如下代码{ "scripts": {"dev": "vite"}, } 运行该我的项目
咱们能够通过如下命令运行该我的项目:
$ npm run dev
呈现如上图片说明我的项目启动胜利,至此,一个简易版的脚手架已实现。
延长
css-module/less/scss
vite
默认是反对 module
的,只需将文件名称加一个 module
即可,如:xx.module.css
, 这样就变成了 module
了,更 create-react-app 一样的写法。
对 scss/less 的反对,装置依赖,如下:
$ npm install less sass -D
css/less
的 module
模式同 css
一样,如:xx.module.scss
,xx.module.less
增加全局 less/scss
变量,如下👇:
-
在
src
文件夹下新增assets
文件夹,且在新增scss
文件夹,在scss
文件夹中新增varible.scss
文件,且在src/assets/scss/varible.scss
中编写如下代码:$bg: #f0f0f0; @mixin flexContainer($jc) { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: $jc; } @mixin style($size, $color, $bold: normal) { font-size: $size; color: $color; font-weight: $bold; } -
在
config
文件夹下,新增style
文件夹,且在style
文件夹下新增index.ts
,config/style/index.ts
中编写如下代码:import {CSSOptions} from 'vite'; const cssOption: CSSOptions = { preprocessorOptions: { less: {javascriptEnabled: true,}, scss: {additionalData: '@import"./src/assets/scss/varible.scss";',}, }, }; export default cssOption; 留神点:
additionalData
中如果援用@import
格局的,前面肯定要加;
否则会报错 - 找到
vite.config.ts
文件,并新增如下代码:
import {defineConfig} from 'vite'; | |
import createVitePlugins from './config/plugins'; | |
+ import cssOption from './config/style'; | |
export default defineConfig((configEnv) => { | |
return {plugins: createVitePlugins(), | |
+ css: cssOption, | |
}; | |
}); |
-
将
src/app.css
中的app.css
换成app.module.scss
, 如:app.css
->app.module.scss
,
更改src/App.tsx
文件中的代码:import React, {FC, useEffect} from 'react'; - import './app.css'; + import styles from './app.module.scss'; const App: FC = () => {useEffect(() => {console.log(`vite-react-cil`); }, []); return (<div className={styles.App}> <h2>Welcome to vite-react-cil</h2> </div> ); }; 环境变量
在
vue-cil
,create-react-app
中,设置
环境变量,能够通过cross-env
+.env
文件设置自定义环境变量,通过process.env
这个来获取
自定义的环境变量,然而在vite
中有点区别。
vite
中 设置 环境变量- 新增
.env
,.env.alpha
,.env.preprod
,.env.prod
四个文件,更src
同级目录.
.env
文件编写如下代码:
NODE_ENV=development | |
VITE_APP_ANT=dev |
.env.alpha
文件编写如下代码:
NODE_ENV=production | |
VITE_APP_ANT=alpha |
.env.preprod
文件编写如下代码:
NODE_ENV=production | |
VITE_APP_ANT=preprod |
.env.prod
文件编写如下代码:
NODE_ENV=production | |
VITE_APP_ANT=prod |
别离代表 开发
, 测试
, 预发
, 生产
四个环境变量,如果想要扩大其它的变量,以此类推.
留神点:
自定义环境变量肯定要是
VITE
为前缀的变量才会裸露给vite
, 如:VITE_APP_SOME
-
找到
package.json
文件,减少如下代码:{ "scripts": { - "dev": "vite", + "dev": "vite --mode dev", + "build:alpha": "vite build --mode alpha", + "build:preprod": "vite build --mode preprod", + "build:prod": "vite build --mode prod" }, } 提醒:
之所以要在
package.json
中的命令加--mode
,是为了笼罩命令应用的默认模式production
,development
-
typescript
环境下申明自定义的环境变量.
在src
文件夹下,新建vite-env.d.ts
文件,src/vite-env.d.ts
文件外面编写如下代码:/// <reference types="vite/client" /> interface ImportMetaEnv {VITE_APP_ANT: 'dev' | 'alpha' | 'preprod' | 'prod';} vite
中 获取 环境变量
在vite
中获取环境变量通过:import.meta.env
来获取的,并不是process.env
,如果要在代码中,每次通过import.meta.env
来获取,写的切实繁琐,不如封装一个办法.
在 src
文件夹下,新建 utils
文件夹,utils
文件夹中新建 index.ts
, 在src/utils/index.ts
中编写如下代码:
export const environmentVariable = () => { | |
const env = import.meta.env.VITE_APP_ANT; | |
let parps = null; | |
switch (env) { | |
case 'dev': | |
parps = 'dev'; | |
break; | |
case 'alpha': | |
parps = 'alpha'; | |
break; | |
case 'preprod': | |
parps = 'preprod'; | |
break; | |
case 'prod': | |
parps = 'prod'; | |
break; | |
default: | |
parps = 'dev'; | |
break; | |
} | |
return parps; | |
}; |
这样,咱们不论在那个中央要用环境变量,只需调用这个 environmentVariable
办法即可。
base/server 配置
-
在
config
文件夹中新建index.ts
,在config/index.ts
中编写如下代码:/** * @description 开发端口 */ export const VITE_APP_PORT = 3000; /** * @description 公共根底门路 */ export const VITE_APP_BASE = '/'; /** * @description 是否主动在浏览器中关上应用程序 */ export const VITE_APP_OPEN = true; 留神:
config
所有文件中不能通过,import.meta.env
来获取环境变量,会报错,要想在config
文件中用环境变量,只能通过vite-config-ts
传入进来,通过configEnv
传入给config
文件,那么config
文件,就必须要写成函数的模式 -
在
config
文件夹中新建setupProxy.ts
文件,用来做自定义代理,config/setupProxy.ts
中编写如下代码:import {ProxyOptions} from 'vite'; const proxy: Record<string, string | ProxyOptions> = { // 字符串简写写法 '/foo': 'http://localhost:4567', // 选项写法 '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), // 更多请参看:https://cn.vitejs.dev/config/#server-proxy }, }; export default proxy; - 找到
vite.config.ts
文件,并新增如下代码:
import {defineConfig} from 'vite'; | |
import createVitePlugins from './config/plugins'; | |
import cssOption from './config/style'; | |
+ import {VITE_APP_BASE, VITE_APP_PORT, VITE_APP_OPEN} from './config'; | |
+ import proxy from './config/setupProxy'; | |
export default defineConfig((configEnv) => { | |
return { | |
+ base: VITE_APP_BASE, | |
plugins: createVitePlugins(), | |
css: cssOption, | |
+ server: { | |
host: true, | |
port: VITE_APP_PORT, | |
open: VITE_APP_OPEN, | |
proxy, | |
}, | |
}; | |
}); |
别名配置
找到 vite.config.ts
文件,并新增如下代码:
先装置path
.
$ npm install path -D
... 省略 | |
+ import path from 'path'; | |
export default defineConfig((configEnv) => { | |
return { | |
... 省略 | |
+ resolve: { | |
alias: {'@': path.resolve(__dirname, 'src'), | |
}, | |
}, | |
}; | |
}); |
build 配置
- 找到
config/index.ts
文件,新增如下代码:
... 省略 | |
/** | |
* @description 是否在打包环境下,开启打包的剖析可视化图 | |
*/ | |
+ export const VITE_APP_VISUALIZER = false; | |
/** | |
* @description 是否在打包环境下,去除 console.log | |
*/ | |
+ export const VITE_APP_CONSOLE = true; | |
/** | |
* @description 打包环境下,删除 debugger | |
*/ | |
+ export const VITE_APP_DEBUGGER = true; | |
/** | |
* @description 打包环境下是否生成 source map 文件 | |
*/ | |
+ export const VITE_APP_SOURCEMAP = false; |
- 在
config/plugins
文件夹中,新建visualizer.ts
文件
装置rollup-plugin-visualizer
$ npm install rollup-plugin-visualizer -D
在 config/plugins/visualizer.ts
文件中,编写如下代码:
import visualizer from 'rollup-plugin-visualizer'; | |
export default function configVisualizerConfig() { | |
return visualizer({ | |
// 将打包的依赖剖析可视化页面,写到 node_modules 中,这样不占地位 | |
filename: './node_modules/.cache/visualizer/stats.html', | |
open: true, | |
gzipSize: true, | |
brotliSize: true, | |
}); | |
} |
- 找到
config/plugins/index.ts
文件,新增如下代码:
import {Plugin} from 'vite'; | |
import reactRefresh from '@vitejs/plugin-react-refresh'; | |
+ import {VITE_APP_VISUALIZER} from '../index'; | |
+ import configVisualizerConfig from './visualizer'; | |
export default function createVitePlugins() {const vitePlugins: (Plugin | Plugin[])[] = [reactRefresh(), | |
]; | |
+ VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig()); | |
return vitePlugins; | |
} |
- 在
config
文件夹下,新建build.ts
文件,且编写如下代码:
import {BuildOptions} from 'vite'; | |
import {VITE_APP_CONSOLE, VITE_APP_DEBUGGER, VITE_APP_SOURCEMAP} from '../config'; | |
const build: BuildOptions = { | |
terserOptions: { | |
compress: { | |
keep_infinity: true, | |
drop_console: VITE_APP_CONSOLE, | |
drop_debugger: VITE_APP_DEBUGGER, | |
}, | |
}, | |
outDir: 'dist', // 指定输入门路目录 | |
assetsDir: 'assets', // 指定打包生成动态资源的寄存门路目录 | |
sourcemap: VITE_APP_SOURCEMAP, // 构建后是否生成 source map 文件 | |
}; | |
export default build; |
- 找到
vite.config.ts
文件,新增如下代码:
... 省略 | |
+ import build from './config/build'; | |
export default defineConfig((configEnv) => { | |
return { | |
... 省略 | |
+ build | |
}; | |
}); |
进阶
eslint
-
先装置如下的依赖:
$ npm install @typescript-eslint/eslint-plugin eslint eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier @typescript-eslint/parser eslint-config-prettier eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-simple-import-sort -D
提醒:
如上这些依赖,更具自已的状况装置,我这里就全副装置了,其中
@typescript-eslint/eslint-plugin
,eslint-plugin-react
,eslint-plugin-react-hooks
这几个依赖绝对其它的来说,重要一些,倡议装置. -
新建
.eslintrc.js
,.eslintignore
两个文件,更src
同级目录..eslintrc.js
文件写下如下代码:module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2020, sourceType: 'module', ecmaFeatures: {jsx: true,}, }, settings: { react: {version: 'detect',}, }, env: { browser: true, amd: true, node: true, }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:react-hooks/recommended', 'plugin:jsx-a11y/recommended', 'plugin:prettier/recommended', ], plugins: ['simple-import-sort', 'prettier'], rules: {'prettier/prettier': ['error', {}, {usePrettierrc: true}], 'react/react-in-jsx-scope': 'off', 'jsx-a11y/accessible-emoji': 'off', 'react/prop-types': 'off', '@typescript-eslint/explicit-function-return-type': 'off', 'simple-import-sort/imports': 'off', 'simple-import-sort/exports': 'error', 'jsx-a11y/anchor-is-valid': [ 'error', {components: ['Link'], specialLink: ['hrefLeft', 'hrefRight'], aspects: ['invalidHref', 'preferButton'], }, ], 'no-debugger': 0, eqeqeq: 2, 'default-case': 1, 'no-empty-function': 1, 'no-multi-spaces': 1, 'spaced-comment': ['error', 'always'], 'no-multiple-empty-lines': ['error', { max: 3}], }, }; 提醒:
如上的
eslint
配置,大家能够没必要更我的一样,能够更具自已的理论状况,进行对应的eslint
配置,配置参照 eslint 官网..eslintignore
文件写下如下代码:node_modules .DS_Store dist coverage src/__tests__ __tests__ dist-ssr *.local node_modules/* - 找到
package.json
文件,新增如下代码:
... 省略 | |
+ "lint": "eslint ./src --ext .jsx,.js,.ts,.tsx", | |
+ "lint:fix": "eslint ./src --ext .jsx,.js,.ts,.tsx --fix", |
npm run lint
命令,能够检测 src
文件外面所有不标准的代码.
npm run lint:fix
命令,能够主动修复 src
文件外面所有不标准的代码.
😦,当初咱们的确能够检测代码标准了,然而有一个问题,这些检测的代码必须要我敲命令,而且不是在开发模式下 主动
检测的,这个行为很不敌对,像 webpack
中咱们能够用 eslint-loader
在开发模式下自动检测,那么 vite
也有相似 eslint-loader
的插件吗?当然有.
-
装置如下依赖:
$ npm install vite-plugin-checker -D
- 找到
config/index.ts
文件,新增如下代码:
/** | |
* @description 是否在开发模式下,启动 eslint | |
*/ | |
+ export const VITE_APP_ESLINT = true; |
- 找到
config/plugins
文件夹,新建eslint.ts
文件,且在config/plugins/eslint.ts
文件中编写如下代码:
import checker from 'vite-plugin-checker'; | |
export default function configEslint() { | |
return [ | |
checker({ | |
typescript: true, | |
eslint: {files: ['./src'], | |
extensions: ['.ts', '.tsx', '.jsx'], | |
}, | |
}), | |
]; | |
} |
提醒:
这里我不举荐大家用
vite-plugin-eslint
这个插件,这个插件在检测谬误时,会阻止热更新.
- 找到
config/plugins/index.ts
文件, 新增如下代码:
import {Plugin} from 'vite'; | |
import reactRefresh from '@vitejs/plugin-react-refresh'; | |
+ import {VITE_APP_VISUALIZER,VITE_APP_ESLINT} from '../index'; | |
import configVisualizerConfig from './visualizer'; | |
+ import configEslint from './eslint'; | |
export default function createVitePlugins() {const vitePlugins: (Plugin | Plugin[])[] = [reactRefresh(), | |
]; | |
VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig()); | |
+ VITE_APP_ESLINT && vitePlugins.push(...configEslint()); | |
return vitePlugins; | |
} |
到这里,咱们就配置好了一个开发环境下,自动检测的配置。
jest
-
装置如下依赖:
$ npm install @testing-library/jest-dom @types/jest jest ts-jest identity-obj-proxy -D
-
新增
jest.config.js
文件,同src
同级,且编写如下代码:module.exports = { preset: 'ts-jest', roots: ['<rootDir>/src'], moduleDirectories: ['node_modules', 'src'], transform: { '^.+\\.tsx$': 'ts-jest', '^.+\\.ts$': 'ts-jest', }, testRegex: '(/__tests__/.*.(test|spec)).(jsx?|tsx?)$', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], collectCoverage: true, collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx,js,jsx}'], coverageDirectory: '<rootDir>/coverage/', verbose: true, testTimeout: 30000, testEnvironment: 'jsdom', coveragePathIgnorePatterns: ['<rootDir>/node_modules/', '(.*).d.ts$'], moduleNameMapper: {'^.+\\.module\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'identity-obj-proxy', }, }; 提醒:
每个公司对
jest
的配置是不一样的,所以不肯定依照我的配置来,jest
的配置能够参照 jest 官网 -
在
src
文件夹下,新增__tests__
文件夹,且在__tests__
文件夹中在新增App.test.tsx
文件,并编写如下代码:import React from 'react'; import {render, cleanup, getByTestId} from '@testing-library/react'; import '@testing-library/jest-dom'; import App from '../App'; afterEach(cleanup); describe('<App />', () => {it('renders without errors', () => {const { container} = render(<App />); // a 标签含有 data-testid='aNoDisabled', 进行查看 expect(getByTestId(container, 'aNoDisabled')).not.toBeDisabled();}); }); 提醒:
每个人的测试格调不一样,大家能够更具自已的测试格调来测试,能够依照,
组件
,模块
,办法
等形式来编写不同的test
, 我这里就介绍一个繁难的
4 . 找到 package.json
文件,新增如下代码:
... 省略 | |
+ "test": "jest --colors --passWithNoTests", | |
+ "test:watch": "jest --watchAll" |
提醒:
如果感觉自已配置
jest
比较复杂的话,能够举荐大家用 vite-plugin-test
svg 按名导入
如果咱们要引入多个 svg
文件的话,通常的做法是 import xx from 'xx.svg
这样,写多个 import
, 要么在js
中通过 require
数组列表来引入多个,还有的是间接通过操作获取文件夹下,所有的svg
,而后遍历等办法,这些计划大多太繁琐了。
webpack
中能够通过 svg-sprite-loader
这个插件来缩小咱们的操作,间接写入 svg
的名字就能够间接引入了,十分的不便.
vite
中也是能够做到的,通过 vite-plugin-svg-icons
插件,具体实现如下:
-
装置依赖
$ npm install vite-plugin-svg-icons -D
- 在
src
文件夹下,新建icons
文件夹,且在icons
文件夹中,增加一个logon.svg
文件. -
plugins
文件夹下,新建svgIcons.ts
文件,编写如下代码:import viteSvgIcons from 'vite-plugin-svg-icons'; import path from 'path'; export default function configSvgIcons() { return viteSvgIcons({iconDirs: [path.resolve(process.cwd(), 'src/icons')], symbolId: 'icon-[dir]-[name]', }); } - 在
config/plugins/index.ts
中,增加如下代码:
+ import configSvgIcons from './svgIcons'; | |
import {Plugin} from 'vite'; | |
import reactRefresh from '@vitejs/plugin-react-refresh'; | |
export default function createVitePlugins() {const vitePlugins: (Plugin | Plugin[])[] = [reactRefresh(), | |
+ configSvgIcons()]; | |
... 省略 | |
return vitePlugins; | |
} |
5 在 src
文件夹下,新建 components
文件夹,在 components
文件夹中新建文件夹 svgIcon
文件夹,最初在 src/components/svgIcon
文件夹下,新建index.tsx
, 且编写如下代码:
import React, {memo, useMemo} from 'react'; | |
export type svgProps = { | |
iconClass: string; | |
fill?: string; | |
fontSize?: string; | |
className?: string; | |
style?: React.CSSProperties; | |
onClick?: React.MouseEventHandler<SVGSVGElement>; | |
}; | |
const SvgIcon: React.FC<svgProps> = memo(function SvgIcon({ | |
iconClass, | |
fill, | |
fontSize = '18px', | |
className, | |
onClick, | |
style, | |
}) {const iconName = useMemo(() => '#icon-' + iconClass, [iconClass]); | |
return ( | |
<svg | |
fontSize={fontSize!} | |
style={{...svgStyle, fontSize, ...style}} | |
aria-hidden="true" | |
className={className!} | |
onClick={onClick} | |
> | |
<use xlinkHref={iconName} fill={fill!} /> | |
</svg> | |
); | |
}); | |
const svgStyle = { | |
width: '1em', | |
height: '1em', | |
verticalAlign: '-0.15em', | |
overflow: 'hidden', | |
fill: 'currentColor', | |
fontSize: '1.1em', | |
}; | |
export default SvgIcon; |
6 在 src/main.tsx
文件中, 增加如下的代码:
+ import 'virtual:svg-icons-register'; | |
... 省略 |
- 应用,在
src/App.tsx
文件中,增加如下代码:
... 省略 | |
+ import SvgComponent from './components/svgIcon'; | |
const App: FC = () => { | |
return (<div className={styles.App}> | |
<h2>Welcome to vite-react-cil</h2> | |
+ <SvgComponent iconClass="logon" fontSize="30px" /> | |
</div> | |
); | |
}; | |
export default App; |
第三方 ui 组件,按需导入
我的项目中,可能会用到 antd
,element
等 ui 组件,咱们个别都是按需引入进来的,不会全副引入,这样会造成打包的时候,包很大,vite
具体操作如下:
-
装置依赖
$ npm install vite-plugin-style-import -D
$ npm install antd -S
-
在
config/plugins
文件夹下,新建styleImport.ts
文件, 编写如下代码:import styleImport from 'vite-plugin-style-import'; export default function configStyleImport() { return styleImport({ libs: [ { libraryName: 'antd', esModule: true, resolveStyle: (name) => {return `antd/es/${name}/style/index`; }, }, ], }); } - 在
config/plugins/index.ts
中,增加如下的代码:
+ import configStyleImport from './styleImport'; | |
import {Plugin} from 'vite'; | |
import reactRefresh from '@vitejs/plugin-react-refresh'; | |
export default function createVitePlugins() {const vitePlugins: (Plugin | Plugin[])[] = [reactRefresh(), | |
... 省略 | |
+ configStyleImport()]; | |
... 省略 | |
return vitePlugins; | |
} |
prettierrc 格式化代码
装置如下依赖:
$ npm install prettier -D
vscode
编辑器装置 Prettier - Code formatter
插件,一起配合的应用.
- 新增
.prettierignore
,.prettierrc
这两个文件,更src
同级目录
.prettierrc
编写如下代码:
{ | |
"singleQuote": true, | |
"trailingComma": "all", | |
"prettier.tabWidth": 2, | |
"editor.defaultFormatter": "esbenp.prettier-vscode", | |
"[typescript]": {"editor.defaultFormatter": "esbenp.prettier-vscode"}, | |
"": {"editor.defaultFormatter":"esbenp.prettier-vscode"},"": {"editor.defaultFormatter": "esbenp.prettier-vscode"}, | |
"[scss]": {"editor.defaultFormatter": "esbenp.prettier-vscode"}, | |
"overrides": [ | |
{ | |
"files": ".prettierrc", | |
"options": {"parser": "json"} | |
} | |
] | |
} |
提醒:
prettierrc
的配置文件也能够是一个js
文件,prettierrc
的具体配置用法,能够参看官网.prettierignore
编写如下代码:
**/*.md | |
**/*.svg | |
**/*.ejs | |
**/*.html | |
package.json |
-
在
package.json
中新增如下的代码:{ "scripts": {"format": "prettier --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\"", } } 输出
npm run format
即可格式化代码
mock
mock
我这边用的较少,根本都是自已写 serve
接口,举荐大家用 vite-plugin-mock 插件,配置的话,更我后面介绍的插件配置大同小异, 在 config/plugins
中新建 configMock.ts
, 在新建一个mock
文件夹,用来寄存模仿异步的接口,mock
文件夹更 src
目录同级.
editorconfig
团队代码格调对立配置,这里举荐大家用editorconfig
.
vscode
编辑器装置插件EditorConfig for VS Code
, 当然,其它的编辑器也是能够的,只是要下对应的editorconfig
插件,我这里就以vscode
为主.-
新建
.editorconfig
文件,同src
同级目录,编写如下代码:[*.{js,jsx,ts,tsx,vue}] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true max_line_length = 100 提醒:
每个团队的代码格调配置是不统一的,这个须要依据自已团队的理论状况来配置
部署
每个公司的部署都不雷同,有的用 jenkins
,gh-pages
,docker
等,所以部署这块,大家能够去看看其它的文章,我这里就不论述了.
总结
通过后面的一步一步的搭建,最终的我的项目整体构造如下:
├── config | |
│ ├── plugins | |
│ ├── style | |
│ ├── build.ts | |
│ ├── index.ts | |
│ ├── setupProxy.ts | |
├── public | |
├── mock | |
├── src | |
│ ├── __tests__ | |
│ ├── assets | |
│ ├── components | |
│ ├── icons | |
│ ├── utils | |
│ ├── app.module.scss | |
│ ├── App.tsx | |
│ ├── main.tsx | |
│ ├── vite-env.d.ts | |
├── .editorconfig | |
├── .env | |
├── .env.alpha | |
├── .env.preprod | |
├── .env.prod | |
├── .eslintignore | |
├── .eslintrc.js | |
├── .gitignore | |
├── .prettierignore | |
├── .prettierrc | |
├── jest.config.js | |
├── index.html | |
├── tsconfig.json | |
├── vite.config.ts | |
└── package.json |
论断:
vite
尽管是新起之秀,但毛病也是很显著的,生态还没有齐全的遍及开来,当初仍旧是webpack
主宰者,构建方面的劣势。vite
在性能方面的确要比webpack
好,而且因为vite
的起因,当初有很多人晓得了rollup
, 不论怎么样,vite
都是值得去学习和理解的.-
咱们也不能自觉的随风逐流,看到人家公司用
vite
, 自已也想将公司的我的项目重形成vite
, 因更具理论状况而来决定。我的项目地址 / 案例实战
我的项目地址👉vite-react-cil.
案例实战:
- ant-simple-pro 是一款反对
vue3
,react
,angular
3 大框架的中台解决方案,3.0
版已全副用vite
重构。 -
JoL-player 是一款功能强大的
react
播放器,typescript
开发,bate3.0
版用vite
重构激励
这篇文章,是笔者在 10.1 其间写的,尽管不是很高大尚的文章,但也是用心写了的,还心愿各位小伙伴们,激励一下👍,这样笔者我将更加的有能源了💪。