diff --git a/packages/vite-plugin-uni/__tests__/resolve.spec.ts b/packages/vite-plugin-uni/__tests__/resolve.spec.ts new file mode 100644 index 0000000000..1419ce9656 --- /dev/null +++ b/packages/vite-plugin-uni/__tests__/resolve.spec.ts @@ -0,0 +1,66 @@ +import os from 'os' +import path from 'path' +import fs from 'fs-extra' +import type { PluginContext } from 'rollup' + +import { customResolver } from '../src/config/resolve' + +describe('resolve', () => { + const originalEnv = { + UNI_PLATFORM: process.env.UNI_PLATFORM, + UNI_UTS_PLATFORM: process.env.UNI_UTS_PLATFORM, + UNI_INPUT_DIR: process.env.UNI_INPUT_DIR, + UNI_APP_X: process.env.UNI_APP_X, + } + + let inputDir = '' + + beforeEach(() => { + inputDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'vite-plugin-uni-resolve-') + ) + process.env.UNI_PLATFORM = 'app' + process.env.UNI_UTS_PLATFORM = 'app-android' + process.env.UNI_INPUT_DIR = inputDir + process.env.UNI_APP_X = 'false' + + fs.outputFileSync( + path.join( + inputDir, + 'uni_modules/uts-button/utssdk/app-android/index.uts' + ), + 'export const utsButton = 1' + ) + }) + + afterEach(() => { + Object.entries(originalEnv).forEach(([key, value]) => { + if (value === undefined) { + Reflect.deleteProperty(process.env, key) + } else { + process.env[key] = value + } + }) + if (inputDir) { + fs.removeSync(inputDir) + } + }) + + test('customResolver prefixes app uts absolute paths with /@fs/ on Windows', () => { + const utsModuleDir = path.join(inputDir, 'uni_modules/uts-button') + const pluginContext = {} as PluginContext + const resolved = customResolver.call( + pluginContext, + utsModuleDir, + undefined, + { + attributes: {}, + isEntry: false, + } + ) + + expect(resolved).toBe( + '/@fs/' + utsModuleDir.replace(/\\/g, '/') + '?uts-proxy' + ) + }) +}) diff --git a/packages/vite-plugin-uni/src/config/resolve.ts b/packages/vite-plugin-uni/src/config/resolve.ts index 63239c660a..85639a3189 100644 --- a/packages/vite-plugin-uni/src/config/resolve.ts +++ b/packages/vite-plugin-uni/src/config/resolve.ts @@ -1,6 +1,7 @@ import path from 'path' import type { Alias, ResolverFunction, UserConfig } from 'vite' import { + FS_PREFIX, extensions, isNormalCompileTarget, isWindows, @@ -16,11 +17,14 @@ import type { VitePluginUniResolvedOptions } from '..' function resolveUTSModuleProxyFile(id: string, importer: string) { const file = resolveUTSAppModule(process.env.UNI_UTS_PLATFORM, id, importer) if (file) { + const normalizedFile = isWindows ? normalizePath(file) : file // app-js 会返回完整路径,不需要 uts-proxy - if (file.endsWith('.uts')) { - return file + if (normalizedFile.endsWith('.uts')) { + return isWindows ? FS_PREFIX + normalizedFile : normalizedFile } - return file + '?uts-proxy' + return isWindows + ? `${FS_PREFIX + normalizedFile}?uts-proxy` + : normalizedFile + '?uts-proxy' } }