Skip to content

Commit

Permalink
refactor: 将vite plugin 提取到plugins目录中优化目录结构
Browse files Browse the repository at this point in the history
  • Loading branch information
yuntian001 committed Jan 5, 2023
1 parent 58c6f8d commit d121f11
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 152 deletions.
10 changes: 10 additions & 0 deletions plugins/autoComponents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { resolver } from './autoImport';
export default () =>
Components({
// 组件自动注册(包括components下的所有.vue组件和ElementPlus组件)
include: [],
dts: false,
resolvers: [ElementPlusResolver({ importStyle: false }), resolver([3], [2])],
});
61 changes: 61 additions & 0 deletions plugins/autoImport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { resolve } from 'path';
import * as fs from 'fs';
import { createPlugin } from 'vite-plugin-autogeneration-import-file';
const { autoImport, resolver: resolverFn } = createPlugin();
function pathResolve(dir: string) {
return resolve(__dirname, '../', dir);
}
export default () =>
autoImport([
// 自动生成
{
// svg icon type
pattern: ['*.svg'],
dir: pathResolve('src/icons/svg'),
toFile: pathResolve('types/meIconComments.d.ts'),
name: 'MeIcon_{{name}}',
template: fs.readFileSync(pathResolve('./template/meIconComments.d.ts'), 'utf-8'),
codeTemplates: [{ key: '//code', template: '{{name}}: Icon;\n ' }],
},
{
// pinia module
pattern: ['**/*.{ts,js}', '*.{ts,js}'],
dir: pathResolve('src/store/modules'),
toFile: pathResolve('src/store/module.ts'),
name: 'use_{{name}}_store',
},
{
// auto import directives
pattern: ['*.ts', '**/index.ts'],
dir: pathResolve('src/directives'),
toFile: pathResolve('types/directives.d.ts'),
template: fs.readFileSync(pathResolve('./template/directives.d.ts'), 'utf-8'),
codeTemplates: [
{
key: '//code',
template: '{{name}}: typeof import("{{path}}")["default"];\n ',
},
],
name: 'V_{{name}}',
},
{
// auto import components
pattern: ['*.{vue,ts}', '**/index.{vue,ts}'],
dir: pathResolve('src/components'),
toFile: pathResolve('types/components.d.ts'),
template: fs.readFileSync(pathResolve('./template/components.d.ts'), 'utf-8'),
codeTemplates: [
{
key: '//code',
template: '{{name}}: typeof import("{{path}}")["default"];\n ',
},
{
key: '//typeCode',
template: 'type {{name}}Instance = InstanceType<typeof import("{{path}}")["default"]>;\n ',
},
],
name: '_{{name}}',
},
]);

export const resolver = resolverFn;
14 changes: 14 additions & 0 deletions plugins/autoImportApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import AutoImport from 'unplugin-auto-import/vite';
import { resolve } from 'path';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
function pathResolve(dir: string) {
return resolve(__dirname, '../', dir);
}
export default () =>
AutoImport({
// 自动加载API
imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
// 可以选择auto-imports.d.ts生成的位置,使用ts建议设置为'src/auto-imports.d.ts'
dts: pathResolve('types/auto-imports.d.ts'),
resolvers: [ElementPlusResolver()],
});
25 changes: 25 additions & 0 deletions plugins/babel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { babel } from '@rollup/plugin-babel';
import { createRequire } from 'node:module';
export default () =>
babel({
babelrc: false,
extensions: ['.ts', '.tsx'],
plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]],
presets: [
[
'@babel/preset-env',
{
targets: ['chrome 87', 'safari 13', 'firefox 78', 'edge 88'],
useBuiltIns: 'usage',
bugfixes: true,
loose: false,
modules: false,
corejs: createRequire(import.meta.url)('core-js/package.json').version,
shippedProposals: true,
ignoreBrowserslistConfig: true,
},
],
],
exclude: 'node_modules/**',
babelHelpers: 'runtime',
});
34 changes: 34 additions & 0 deletions plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { ConfigEnv } from 'vite';
import autoComponents from './autoComponents';
import autoImport from './autoImport';
import autoImportApi from './autoImportApi';
import babel from './babel';
import mock from './mock';
import svgLoader from './svgLoader';
import vueSetUpExtend from './vueSetUpExtend';
import { visualizer } from 'rollup-plugin-visualizer'; //打包大小分析(stats.html)
import vue from '@vitejs/plugin-vue';
// import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import { splitVendorChunkPlugin } from 'vite';
import viteCompression from 'vite-plugin-compression'; //打包压缩

export default (configEnv: ConfigEnv) => {
return [
vue(),
splitVendorChunkPlugin(), //打包分析,会生成stats.html展示打包情况
// VueI18nPlugin({
// /* options */
// // locale messages resource pre-compile option
// include: ['./src/**/lang/**/*.json', './src/**/lang/*.json'],
// }),
visualizer(),
viteCompression(),
autoComponents(),
autoImport(),
autoImportApi(),
babel(),
mock(configEnv),
svgLoader(),
vueSetUpExtend(),
];
};
13 changes: 13 additions & 0 deletions plugins/mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { viteMockServe } from '@meadmin-cn/vite-plugin-mock';
import { ConfigEnv } from 'vite';
export default ({ command }: ConfigEnv) =>
viteMockServe({
mockPath: 'mock/apiDemo',
localEnabled: command === 'serve',
prodEnabled: command !== 'serve',
// 这样可以控制关闭mock的时候不让mock打包到最终代码内
injectCode: `
import { setupProdMockServer } from '../mock/index';
setupProdMockServer();
`,
});
22 changes: 22 additions & 0 deletions plugins/svgLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import svgLoader from 'vite-svg-loader';
export default () =>
svgLoader({
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false, // 禁用插件
},
},
},
{
name: 'removeAttrs',
params: {
attrs: '(width|height|fill)', // 清除svg属性
},
},
],
},
});
9 changes: 9 additions & 0 deletions plugins/vueSetUpExtend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { vueSetUpExtend } from '@yuntian001/vue-setup-extend';
// @ts-ignore
import { loadMessageConfig } from '../src/config/locale';
export default () =>
vueSetUpExtend({
exclude: ['steup', 'lang'],
setLangImport: loadMessageConfig.componentLoad,
setComponents: loadMessageConfig.componentLoad,
});
2 changes: 1 addition & 1 deletion tsconfig.node.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
"moduleResolution": "node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts", "./plugin/vueSetupExtend.ts"]
"include": ["vite.config.ts", "./plugins/*.ts"]
}
154 changes: 3 additions & 151 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,166 +1,18 @@
import { createRequire } from 'node:module';
import vue from '@vitejs/plugin-vue';
import svgLoader from 'vite-svg-loader';
import { resolve } from 'path';
import * as fs from 'fs';
import { createPlugin } from 'vite-plugin-autogeneration-import-file';
import { vueSetUpExtend } from '@yuntian001/vue-setup-extend';
import { viteMockServe } from '@meadmin-cn/vite-plugin-mock';
import { ConfigEnv, UserConfigExport } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer'; //打包大小分析(stats.html)
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
// import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import { splitVendorChunkPlugin } from 'vite';
import autoprefixer from 'autoprefixer';
import plugins from './plugins';
// @ts-ignore
import px2rem from 'postcss-plugin-px2rem';
import viteCompression from 'vite-plugin-compression'; //打包压缩
import { babel } from '@rollup/plugin-babel';

// @ts-ignore
import { loadMessageConfig } from './src/config/locale';
function pathResolve(dir: string) {
return resolve(__dirname, '.', dir);
}

const { autoImport, resolver } = createPlugin();
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
export default async (configEnv: ConfigEnv): Promise<UserConfigExport> => {
return {
envPrefix: 'ME_',
plugins: [
babel({
babelrc: false,
extensions: ['.ts', '.tsx'],
plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]],
presets: [
[
'@babel/preset-env',
{
targets: ['chrome 87', 'safari 13', 'firefox 78', 'edge 88'],
useBuiltIns: 'usage',
bugfixes: true,
loose: false,
modules: false,
corejs: createRequire(import.meta.url)('core-js/package.json').version,
shippedProposals: true,
ignoreBrowserslistConfig: true,
},
],
],
exclude: 'node_modules/**',
babelHelpers: 'runtime',
}),
vueSetUpExtend({
exclude: ['steup', 'lang'],
setLangImport: loadMessageConfig.componentLoad,
setComponents: loadMessageConfig.componentLoad,
}),
splitVendorChunkPlugin(), //打包分析,会生成stats.html展示打包情况
// VueI18nPlugin({
// /* options */
// // locale messages resource pre-compile option
// include: ['./src/**/lang/**/*.json', './src/**/lang/*.json'],
// }),
viteMockServe({
mockPath: 'mock/apiDemo',
localEnabled: command === 'serve',
prodEnabled: command !== 'serve',
// 这样可以控制关闭mock的时候不让mock打包到最终代码内
injectCode: `
import { setupProdMockServer } from '../mock/index';
setupProdMockServer();
`,
}),
AutoImport({
// 自动加载API
imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
// 可以选择auto-imports.d.ts生成的位置,使用ts建议设置为'src/auto-imports.d.ts'
dts: pathResolve('types/auto-imports.d.ts'),
resolvers: [ElementPlusResolver()],
}),
Components({
// 组件自动注册(包括components下的所有.vue组件和ElementPlus组件)
include: [],
dts: false,
resolvers: [ElementPlusResolver({ importStyle: false }), resolver([3], [2])],
}),
vue(),
svgLoader({
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false, // 禁用插件
},
},
},
{
name: 'removeAttrs',
params: {
attrs: '(width|height|fill)', // 清除svg属性
},
},
],
},
}),
autoImport([
// 自动生成
{
// svg icon type
pattern: ['*.svg'],
dir: pathResolve('src/icons/svg'),
toFile: pathResolve('types/meIconComments.d.ts'),
name: 'MeIcon_{{name}}',
template: fs.readFileSync(pathResolve('./template/meIconComments.d.ts'), 'utf-8'),
codeTemplates: [{ key: '//code', template: '{{name}}: Icon;\n ' }],
},
{
// pinia module
pattern: ['**/*.{ts,js}', '*.{ts,js}'],
dir: pathResolve('src/store/modules'),
toFile: pathResolve('src/store/module.ts'),
name: 'use_{{name}}_store',
},
{
// auto import directives
pattern: ['*.ts', '**/index.ts'],
dir: pathResolve('src/directives'),
toFile: pathResolve('types/directives.d.ts'),
template: fs.readFileSync(pathResolve('./template/directives.d.ts'), 'utf-8'),
codeTemplates: [
{
key: '//code',
template: '{{name}}: typeof import("{{path}}")["default"];\n ',
},
],
name: 'V_{{name}}',
},
{
// auto import components
pattern: ['*.{vue,ts}', '**/index.{vue,ts}'],
dir: pathResolve('src/components'),
toFile: pathResolve('types/components.d.ts'),
template: fs.readFileSync(pathResolve('./template/components.d.ts'), 'utf-8'),
codeTemplates: [
{
key: '//code',
template: '{{name}}: typeof import("{{path}}")["default"];\n ',
},
{
key: '//typeCode',
template: 'type {{name}}Instance = InstanceType<typeof import("{{path}}")["default"]>;\n ',
},
],
name: '_{{name}}',
},
]),
visualizer(),
viteCompression(),
],
plugins: await plugins(configEnv),
css: {
preprocessorOptions: {
scss: {
Expand Down

0 comments on commit d121f11

Please sign in to comment.