Vite插件快速识别-日常开发篇
1、打包构建后移除console.log和注释:vite官方自带
// vite.config.ts
import { defineConfig } from 'vite'
export default defineConfig({
build:{
minify: 'terser',
terserOptions: {
//打包后移除console和注释
compress: {
drop_console: true,
drop_debugger: true,
},
},
},
})
2、实现vue函数和组件库的自动按需导入:unplugin-auto-import
插件和unplugin-vue-components
插件实现
pnpm i unplugin-auto-import unplugin-vue-components -D
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import ViteComponents from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
...
AutoImport({
include: [
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
/\.vue$/,
/\.vue\?vue/, // .vue
/\.md$/, // .md
],
dts: true,
imports: ['vue', 'vue-router'],
}),
ViteComponents({
dts: true,
resolvers: [VantResolver()],
}),
],
})
// tsconfig.json 需要校验的文件后缀集合
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx","src/**/*.vue","components.d.ts","auto-imports.d.ts"],
3、自动引入组件库的样式以ElementPlus为参考:vite-plugin-style-import插件实现
npm i vite-plugin-style-import -D
// vite.config.ts
import {
createStyleImportPlugin,
ElementPlusResolve,
} from 'vite-plugin-style-import';
export default defineConfig({
plgins: [
createStyleImportPlugin({
resolves: [ElementPlusResolve()],
libs: [
{
libraryName: 'element-plus',
esModule: true,
resolveStyle: (name: string) => {
name = name.substring(3, name.length);
return `element-plus/es/components/${name}/style/index`;
},
},
],
}),
]
});
4、Vite 仅执行 .ts
文件的转译工作,并不执行任何类型检查。vite-plugin-checker
插件实现对代码进行有效约束
npm install vite-plugin-checker -D
// vite.config.ts
export default defineConfig({
plugins: [checker({
typescript: true
})]
})