import path from 'node:path' import process from 'node:process' import Uni from '@uni-helper/plugin-uni' import UniComponents from '@uni-helper/vite-plugin-uni-components' // @see https://uni-helper.js.org/vite-plugin-uni-layouts import UniLayouts from '@uni-helper/vite-plugin-uni-layouts' // @see https://github.com/uni-helper/vite-plugin-uni-manifest import UniManifest from '@uni-helper/vite-plugin-uni-manifest' // @see https://uni-helper.js.org/vite-plugin-uni-pages import UniPages from '@uni-helper/vite-plugin-uni-pages' import { WotResolver } from './wot-ui-resolver' // @see https://github.com/uni-helper/vite-plugin-uni-platform // 需要与 @uni-helper/vite-plugin-uni-pages 插件一起使用 import UniPlatform from '@uni-helper/vite-plugin-uni-platform' /** * 分包优化、模块异步跨包调用、组件异步跨包引用 * @see https://github.com/uni-ku/bundle-optimizer */ // https://github.com/uni-ku/root import UniKuRoot from '@uni-ku/root' import dayjs from 'dayjs' import { visualizer } from 'rollup-plugin-visualizer' import UnoCSS from 'unocss/vite' import AutoImport from 'unplugin-auto-import/vite' import { defineConfig, loadEnv } from 'vite' import ViteRestart from 'vite-plugin-restart' import openDevTools from './scripts/open-dev-tools' import vitePluginEruda from './scripts/vite-plugin-eruda' import { createCopyNativeResourcesPlugin } from './vite-plugins/copy-native-resources' import syncManifestPlugin from './vite-plugins/sync-manifest-plugins' import autoCreateRoutePath from './src/utils/autoCreateRoutePath' import scanPageFilter from './src/utils/scanPageFilter' function disableUniMpWeixinShadowPreloadPlugin() { return { name: 'disable-uni-mp-weixin-shadow-preload', enforce: 'pre' as const, transform(code: string, id: string) { if (!id.includes('@dcloudio/uni-mp-weixin') || !id.endsWith('uni.mp.esm.js') || !code.includes('wx.preloadAssets')) { return null } const nextCode = code.replace( /\s*if \(!\(process\.env\.NODE_ENV !== 'production'\) &&\s*"mp-weixin" === 'mp-weixin' &&\s*isFunction\(wx\.preloadAssets\)\) \{\s*const protocol = 'https';\s*setTimeout\(\(\) => \{\s*wx\.preloadAssets\(\{\s*data: \[\{ type: 'image', src: protocol \+ __UNI_PRELOAD_SHADOW_IMAGE__ \}\],\s*\}\);\s*\}, 3000\);\s*\}/, '', ) return nextCode === code ? null : { code: nextCode, map: null } }, } } const appSubPackageRules = [ { root: 'pages/business/views', paths: [ 'addon/index', 'allocate/index', 'balanceRecharge/index', 'cardRenew/index', 'change/index', 'customer/index', 'customerDetail/index', 'diagnosis/index', 'order/index', 'renew/index', 'warning/index', 'workOrder/index', 'workOrderCreate/index', 'workOrderDetail/index', ], }, { root: 'pages/card/views', paths: [ 'detail/index', 'management/index', 'packageDetail/index', 'warning/index', ], }, { root: 'pages/message/views', paths: [ 'cardDetail/index', 'systemDetail/index', ], }, { root: 'pages/user/views', paths: [ 'about/index', 'agreement/index', 'contact/index', 'feedback/index', 'notification/index', 'profile/index', 'realName/index', ], }, ] function splitAppPagesToSubPackages(ctx: any) { const pageMetaData = Array.isArray(ctx.pageMetaData) ? ctx.pageMetaData : [] const subPackageMap = new Map() const nextMainPages: any[] = [] for (const rule of appSubPackageRules) { subPackageMap.set(rule.root, []) } for (const page of pageMetaData) { const matchedRule = appSubPackageRules.find((rule) => { const prefix = `${rule.root}/` if (!page.path?.startsWith(prefix)) { return false } return rule.paths.includes(page.path.slice(prefix.length)) }) if (!matchedRule) { nextMainPages.push(page) continue } const prefix = `${matchedRule.root}/` subPackageMap.get(matchedRule.root)?.push({ ...page, path: page.path.slice(prefix.length), }) } const generatedSubPackages = Array.from(subPackageMap.entries()) .filter(([, pages]) => pages.length > 0) .map(([root, pages]) => ({ root, pages })) const remainingSubPackages = (ctx.subPageMetaData || []) .filter((item: any) => !subPackageMap.has(item.root)) ctx.pageMetaData = nextMainPages ctx.subPageMetaData = [...remainingSubPackages, ...generatedSubPackages] } // https://vitejs.dev/config/ export default defineConfig(async ({ command, mode }) => { // @see https://unocss.dev/ // const UnoCSS = (await import('unocss/vite')).default // console.log(mode === process.env.NODE_ENV) // true // mode: 区分生产环境还是开发环境 console.log('command, mode -> ', command, mode) // pnpm dev:h5 时得到 => serve development // pnpm build:h5 时得到 => build production // pnpm dev:mp-weixin 时得到 => build development (注意区别,command为build) // pnpm build:mp-weixin 时得到 => build production // pnpm dev:app 时得到 => build development (注意区别,command为build) // pnpm build:app 时得到 => build production // dev 和 build 命令可以分别使用 .env.development 和 .env.production 的环境变量 // 非 H5 端 dev 也是 build command,最终加载哪个 env 文件以实际 mode 为准。 const { UNI_PLATFORM, SKIP_OPEN_DEVTOOLS } = process.env console.log('UNI_PLATFORM -> ', UNI_PLATFORM) // 得到 mp-weixin, h5, app 等 const envDir = path.resolve(process.cwd(), 'env') const env = loadEnv(mode, envDir) const localEnv = loadEnv(mode, envDir, '') const { VITE_APP_PORT, VITE_APP_TITLE, VITE_DELETE_CONSOLE, VITE_APP_PUBLIC_BASE, VITE_COPY_NATIVE_RES_ENABLE, VITE_ERUDA_ENABLE, } = env const { WECHAT_DEVTOOLS_CLI_PATH } = localEnv console.log('环境变量 env -> ', env) process.env.ROOT_DIR = process.env.ROOT_DIR || env.VITE_ROOT_DIR || process.cwd() const isVitest = process.env.VITEST === 'true' const useBundleOptimization = !isVitest const alias = { '@': path.join(process.cwd(), './src'), '@img': path.join(process.cwd(), './src/static/images'), } if (isVitest) { return defineConfig({ envDir: './env', resolve: { alias, }, }) } return defineConfig({ envDir: './env', // 自定义env目录 // H5 使用部署子路径;微信小程序和 App 端保持根路径资源引用。 base: UNI_PLATFORM === 'h5' ? (VITE_APP_PUBLIC_BASE || '/') : '/', plugins: [ disableUniMpWeixinShadowPreloadPlugin(), // UniXXX 需要在 Uni 之前引入 UniLayouts(), UniPlatform(), UniManifest(), UniComponents({ extensions: ['vue'], deep: true, // 是否递归扫描子目录, directoryAsNamespace: false, // 是否把目录名作为命名空间前缀,true 时组件名为 目录名+组件名, dts: mode === 'development' ? 'src/types/components.d.ts' : false, // 自动生成的组件类型声明文件路径(用于 TypeScript 支持) resolvers: [WotResolver()], }), UniPages({ exclude: ['**/components/**/**.*', '**/sections/**/**.*'], // pages 目录为 src/pages,分包目录不能配置在pages目录下!! // 是个数组,可以配置多个,但是不能为pages里面的目录!! // "src/pages-demo" 是unibest demo 预留的,方便后续插入demo示例 // subPackages: ['src/pages-demo'], dts: 'src/types/uni-pages.d.ts', onAfterScanPages: (ctx) => { scanPageFilter(ctx, 'pages') }, onAfterMergePageMetaData: (ctx) => { splitAppPagesToSubPackages(ctx) }, onAfterWriteFile: (ctx) => { autoCreateRoutePath(ctx) }, }), // UniOptimization 插件需要 page.json 文件,故应在 UniPages 插件之后执行 ...(useBundleOptimization ? [ (await import('@uni-ku/bundle-optimizer')).default({ // 当前用户侧小程序首屏依赖多个首页组件。微信开发者工具对异步拆包缓存较敏感, // 先关闭小程序端拆包优化,保证本地预览和真机调试优先稳定渲染。 enable: false, dts: { base: 'src/types', }, logger: false, }), ] : []), // 若存在改变 pages.json 的插件,请将 UniKuRoot 放置其后 UniKuRoot({ excludePages: ['**/components/**/**.*', '**/sections/**/**.*'], }), Uni(), { // 临时解决 dcloudio 官方的 @dcloudio/uni-mp-compiler 出现的编译 BUG // 参考 github issue: https://github.com/dcloudio/uni-app/issues/4952 // 自定义插件禁用 vite:vue 插件的 devToolsEnabled,强制编译 vue 模板时 inline 为 true name: 'fix-vite-plugin-vue', configResolved(config) { const plugin = config.plugins.find(p => p.name === 'vite:vue') if (plugin && plugin.api && plugin.api.options) { plugin.api.options.devToolsEnabled = false } }, }, UnoCSS(), AutoImport({ imports: ['vue', 'uni-app'], dts: 'src/types/auto-import.d.ts', dirs: ['src/hooks'], // 自动导入 hooks vueTemplate: true, // default false }), ViteRestart({ // 通过这个插件,在修改vite.config.js文件则不需要重新运行也生效配置 restart: ['vite.config.js'], }), // h5环境增加 BUILD_TIME 和 BUILD_BRANCH UNI_PLATFORM === 'h5' && { name: 'html-transform', transformIndexHtml(html) { return html .replace('%BUILD_TIME%', dayjs().format('YYYY-MM-DD HH:mm:ss')) .replace('%VITE_APP_TITLE%', VITE_APP_TITLE) }, }, // 打包分析插件,h5 + 生产环境才弹出 UNI_PLATFORM === 'h5' && mode === 'production' && visualizer({ filename: './node_modules/.cache/visualizer/stats.html', open: true, gzipSize: true, brotliSize: true, }), // 原生插件资源复制插件 - 仅在 app 平台且启用时生效 createCopyNativeResourcesPlugin( UNI_PLATFORM === 'app' && VITE_COPY_NATIVE_RES_ENABLE === 'true', { verbose: mode === 'development', // 开发模式显示详细日志 }, ), syncManifestPlugin(), vitePluginEruda({ open: UNI_PLATFORM === 'h5' && mode === 'development' && VITE_ERUDA_ENABLE === 'true', }), // 自动打开开发者工具插件 (必须修改 .env 文件中的 VITE_WX_APPID) // 上传时通过 SKIP_OPEN_DEVTOOLS=true 跳过 command === 'serve' && SKIP_OPEN_DEVTOOLS !== 'true' && WECHAT_DEVTOOLS_CLI_PATH && openDevTools({ mode, wechatDevtoolsCliPath: WECHAT_DEVTOOLS_CLI_PATH, }), ], css: { postcss: { plugins: [ // autoprefixer({ // // 指定目标浏览器 // overrideBrowserslist: ['> 1%', 'last 2 versions'], // }), ], }, }, resolve: { alias, }, server: { host: '0.0.0.0', hmr: true, port: Number.parseInt(VITE_APP_PORT, 10), }, esbuild: { drop: VITE_DELETE_CONSOLE === 'true' ? ['console', 'debugger'] : [], }, build: { sourcemap: false, // 方便非h5端调试 // sourcemap: VITE_SHOW_SOURCEMAP === 'true', // 默认是false target: 'es6', // 开发环境不用压缩 minify: mode === 'development' ? false : 'esbuild', }, }) })