From 2a61dd74f31c58f047c1daefd88bb35ae0335b10 Mon Sep 17 00:00:00 2001 From: Evan You Date: Thu, 17 Dec 2020 16:25:23 -0500 Subject: [PATCH] wip: optimize vue relative asset reference + handle out of root assets --- packages/plugin-vue/package.json | 1 + packages/plugin-vue/src/template.ts | 37 +++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/packages/plugin-vue/package.json b/packages/plugin-vue/package.json index cdf31107..4dabc065 100644 --- a/packages/plugin-vue/package.json +++ b/packages/plugin-vue/package.json @@ -34,6 +34,7 @@ "debug": "^4.3.1", "hash-sum": "^2.0.0", "rollup": "^2.35.1", + "slash": "^3.0.0", "source-map": "^0.6.1" } } diff --git a/packages/plugin-vue/src/template.ts b/packages/plugin-vue/src/template.ts index 5c4ecb14..f7b2e9ac 100644 --- a/packages/plugin-vue/src/template.ts +++ b/packages/plugin-vue/src/template.ts @@ -1,3 +1,5 @@ +import path from 'path' +import slash from 'slash' import { compileTemplate, SFCDescriptor, @@ -92,19 +94,44 @@ export function getTemplateCompilerOptions( } const resolvedScript = getResolvedScript(descriptor, options.ssr) const hasScoped = descriptor.styles.some((s) => s.scoped) + const { id, filename, cssVars } = descriptor + + let transformAssetUrls = options.template?.transformAssetUrls + // inject vite base so that @vue/compiler-sfc can transform relative paths + // directly to absolute paths without incurring an extra import request + if (filename.startsWith(options.root)) { + // TODO account for vite base config + const base = + '/' + slash(path.relative(options.root, path.dirname(filename))) + if (transformAssetUrls && typeof transformAssetUrls === 'object') { + // presence of array fields means this is raw tags config + if ( + Object.keys(transformAssetUrls).some((key) => + Array.isArray((transformAssetUrls as any)[key]) + ) + ) { + transformAssetUrls = { base, tags: transformAssetUrls } as any + } else { + transformAssetUrls = { ...transformAssetUrls, base } + } + } else { + transformAssetUrls = { base } + } + } + return { ...options.template, - id: descriptor.id, + id, + filename, scoped: hasScoped, isProd: options.isProduction, - filename: descriptor.filename, inMap: block.src ? undefined : block.map, ssr: options.ssr, - ssrCssVars: descriptor.cssVars, - transformAssetUrls: options.template?.transformAssetUrls, + ssrCssVars: cssVars, + transformAssetUrls, compilerOptions: { ...options.template?.compilerOptions, - scopeId: hasScoped ? `data-v-${descriptor.id}` : undefined, + scopeId: hasScoped ? `data-v-${id}` : undefined, bindingMetadata: resolvedScript ? resolvedScript.bindings : undefined } }