|
| 1 | +import hash from 'hash-sum' |
| 2 | +import path from 'path' |
| 3 | +import qs from 'querystring' |
| 4 | +import { |
| 5 | + parse, |
| 6 | + rewriteDefault, |
| 7 | + SFCBlock, |
| 8 | + SFCDescriptor |
| 9 | +} from '@vue/compiler-sfc' |
| 10 | +import { ResolvedOptions } from '.' |
| 11 | +import { getPrevDescriptor, setDescriptor } from './utils/descriptorCache' |
| 12 | +import { PluginContext, TransformPluginContext } from 'rollup' |
| 13 | +import { resolveScript } from './script' |
| 14 | +import { transformTemplateInMain } from './template' |
| 15 | +import { isOnlyTemplateChanged } from './handleHotUpdate' |
| 16 | +import { RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map' |
| 17 | +import { createRollupError } from './utils/error' |
| 18 | + |
| 19 | +export async function transformMain( |
| 20 | + code: string, |
| 21 | + filename: string, |
| 22 | + options: ResolvedOptions, |
| 23 | + pluginContext: TransformPluginContext |
| 24 | +) { |
| 25 | + const { root, devServer, isProduction, ssr } = options |
| 26 | + |
| 27 | + // prev descriptor is only set and used for hmr |
| 28 | + const prevDescriptor = getPrevDescriptor(filename) |
| 29 | + const { descriptor, errors } = parse(code, { |
| 30 | + sourceMap: true, |
| 31 | + filename |
| 32 | + }) |
| 33 | + |
| 34 | + // set the id on the descriptor |
| 35 | + const shortFilePath = path |
| 36 | + .relative(root, filename) |
| 37 | + .replace(/^(\.\.[\/\\])+/, '') |
| 38 | + .replace(/\\/g, '/') |
| 39 | + |
| 40 | + descriptor.id = hash( |
| 41 | + isProduction ? shortFilePath + '\n' + code : shortFilePath |
| 42 | + ) |
| 43 | + |
| 44 | + setDescriptor(filename, descriptor) |
| 45 | + |
| 46 | + if (errors.length) { |
| 47 | + errors.forEach((error) => |
| 48 | + pluginContext.error(createRollupError(filename, error)) |
| 49 | + ) |
| 50 | + return null |
| 51 | + } |
| 52 | + |
| 53 | + // feature information |
| 54 | + const hasScoped = descriptor.styles.some((s) => s.scoped) |
| 55 | + |
| 56 | + // script |
| 57 | + const { code: scriptCode, map } = await genScriptCode(descriptor, options) |
| 58 | + |
| 59 | + // template |
| 60 | + // Check if we can use compile template as inlined render function |
| 61 | + // inside <script setup>. This can only be done for build because |
| 62 | + // inlined template cannot be individually hot updated. |
| 63 | + const useInlineTemplate = |
| 64 | + !devServer && |
| 65 | + descriptor.scriptSetup && |
| 66 | + !(descriptor.template && descriptor.template.src) |
| 67 | + const hasTemplateImport = descriptor.template && !useInlineTemplate |
| 68 | + |
| 69 | + let templateCode = '' |
| 70 | + let templateMap |
| 71 | + if (hasTemplateImport) { |
| 72 | + ;({ code: templateCode, map: templateMap } = genTemplateCode( |
| 73 | + descriptor, |
| 74 | + options, |
| 75 | + pluginContext |
| 76 | + )) |
| 77 | + } |
| 78 | + |
| 79 | + const renderReplace = hasTemplateImport |
| 80 | + ? ssr |
| 81 | + ? `_sfc_main.ssrRender = _sfc_ssrRender` |
| 82 | + : `_sfc_main.render = _sfc_render` |
| 83 | + : '' |
| 84 | + |
| 85 | + // styles |
| 86 | + const stylesCode = genStyleCode(descriptor) |
| 87 | + |
| 88 | + // custom blocks |
| 89 | + const customBlocksCode = genCustomBlockCode(descriptor) |
| 90 | + |
| 91 | + const output: string[] = [ |
| 92 | + scriptCode, |
| 93 | + templateCode, |
| 94 | + stylesCode, |
| 95 | + customBlocksCode, |
| 96 | + renderReplace |
| 97 | + ] |
| 98 | + if (hasScoped) { |
| 99 | + output.push( |
| 100 | + `_sfc_main.__scopeId = ${JSON.stringify(`data-v-${descriptor.id}`)}` |
| 101 | + ) |
| 102 | + } |
| 103 | + if (!isProduction) { |
| 104 | + output.push(`_sfc_main.__file = ${JSON.stringify(shortFilePath)}`) |
| 105 | + } else if (devServer) { |
| 106 | + // expose filename during serve for devtools to pickup |
| 107 | + output.push( |
| 108 | + `_sfc_main.__file = ${JSON.stringify(path.basename(shortFilePath))}` |
| 109 | + ) |
| 110 | + } |
| 111 | + output.push('export default _sfc_main') |
| 112 | + |
| 113 | + // HMR |
| 114 | + if (devServer) { |
| 115 | + // check if the template is the only thing that changed |
| 116 | + if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) { |
| 117 | + output.push(`export const _rerender_only = true`) |
| 118 | + } |
| 119 | + output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`) |
| 120 | + output.push( |
| 121 | + `__VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)` |
| 122 | + ) |
| 123 | + output.push( |
| 124 | + `import.meta.hot.accept(({ default: updated, _rerender_only }) => {`, |
| 125 | + ` if (_rerender_only) {`, |
| 126 | + ` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`, |
| 127 | + ` } else {`, |
| 128 | + ` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`, |
| 129 | + ` }`, |
| 130 | + `})` |
| 131 | + ) |
| 132 | + } |
| 133 | + |
| 134 | + // if the template is inlined into the main module (indicated by the presence |
| 135 | + // of templateMap, we need to concatenate the two source maps. |
| 136 | + let resolvedMap = map |
| 137 | + if (map && templateMap) { |
| 138 | + const generator = SourceMapGenerator.fromSourceMap( |
| 139 | + new SourceMapConsumer(map) |
| 140 | + ) |
| 141 | + const offset = scriptCode.match(/\r?\n/g)?.length || 1 |
| 142 | + const templateMapConsumer = new SourceMapConsumer(templateMap) |
| 143 | + templateMapConsumer.eachMapping((m) => { |
| 144 | + generator.addMapping({ |
| 145 | + source: m.source, |
| 146 | + original: { line: m.originalLine, column: m.originalColumn }, |
| 147 | + generated: { |
| 148 | + line: m.generatedLine + offset, |
| 149 | + column: m.generatedColumn |
| 150 | + } |
| 151 | + }) |
| 152 | + }) |
| 153 | + resolvedMap = (generator as any).toJSON() |
| 154 | + // if this is a template only update, we will be reusing a cached version |
| 155 | + // of the main module compile result, which has outdated sourcesContent. |
| 156 | + resolvedMap.sourcesContent = templateMap.sourcesContent |
| 157 | + } |
| 158 | + |
| 159 | + return { |
| 160 | + code: output.join('\n'), |
| 161 | + map: resolvedMap || { |
| 162 | + mappings: '' |
| 163 | + } |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +function genTemplateCode( |
| 168 | + descriptor: SFCDescriptor, |
| 169 | + options: ResolvedOptions, |
| 170 | + pluginContext: PluginContext |
| 171 | +) { |
| 172 | + const renderFnName = options.ssr ? 'ssrRender' : 'render' |
| 173 | + const template = descriptor.template! |
| 174 | + |
| 175 | + // If the template is not using pre-processor AND is not using external src, |
| 176 | + // compile and inline it directly in the main module. When served in vite this |
| 177 | + // saves an extra request per SFC which can improve load performance. |
| 178 | + if (!template.lang && !template.src) { |
| 179 | + return transformTemplateInMain( |
| 180 | + template.content, |
| 181 | + descriptor, |
| 182 | + options, |
| 183 | + pluginContext |
| 184 | + ) |
| 185 | + } else { |
| 186 | + const src = template.src || descriptor.filename |
| 187 | + const srcQuery = template.src ? `&src` : `` |
| 188 | + const attrsQuery = attrsToQuery(template.attrs, 'js', true) |
| 189 | + const query = `?vue&type=template${srcQuery}${attrsQuery}` |
| 190 | + return { |
| 191 | + code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${JSON.stringify( |
| 192 | + src + query |
| 193 | + )}`, |
| 194 | + map: undefined |
| 195 | + } |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +async function genScriptCode( |
| 200 | + descriptor: SFCDescriptor, |
| 201 | + options: ResolvedOptions |
| 202 | +): Promise<{ |
| 203 | + code: string |
| 204 | + map: RawSourceMap |
| 205 | +}> { |
| 206 | + let scriptCode = `const _sfc_main = {}` |
| 207 | + let map |
| 208 | + const script = resolveScript(descriptor, options) |
| 209 | + if (script) { |
| 210 | + // If the script is js/ts and has no external src, it can be directly placed |
| 211 | + // in the main module. |
| 212 | + if ( |
| 213 | + (!script.lang || (script.lang === 'ts' && options.devServer)) && |
| 214 | + !script.src |
| 215 | + ) { |
| 216 | + scriptCode = rewriteDefault(script.content, `_sfc_main`) |
| 217 | + map = script.map |
| 218 | + if (script.lang === 'ts') { |
| 219 | + const result = await options.devServer!.transformWithEsbuild( |
| 220 | + scriptCode, |
| 221 | + descriptor.filename, |
| 222 | + { loader: 'ts' }, |
| 223 | + map |
| 224 | + ) |
| 225 | + scriptCode = result.code |
| 226 | + map = result.map |
| 227 | + } |
| 228 | + } else { |
| 229 | + const src = script.src || descriptor.filename |
| 230 | + const attrsQuery = attrsToQuery(script.attrs, 'js') |
| 231 | + const srcQuery = script.src ? `&src` : `` |
| 232 | + const query = `?vue&type=script${srcQuery}${attrsQuery}` |
| 233 | + const scriptRequest = JSON.stringify(src + query) |
| 234 | + scriptCode = |
| 235 | + `import _sfc_main from ${scriptRequest}\n` + |
| 236 | + `export * from ${scriptRequest}` // support named exports |
| 237 | + } |
| 238 | + } |
| 239 | + return { |
| 240 | + code: scriptCode, |
| 241 | + map: map as any |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +function genStyleCode(descriptor: SFCDescriptor) { |
| 246 | + let stylesCode = `` |
| 247 | + let hasCSSModules = false |
| 248 | + if (descriptor.styles.length) { |
| 249 | + descriptor.styles.forEach((style, i) => { |
| 250 | + const src = style.src || descriptor.filename |
| 251 | + // do not include module in default query, since we use it to indicate |
| 252 | + // that the module needs to export the modules json |
| 253 | + const attrsQuery = attrsToQuery(style.attrs, 'css') |
| 254 | + const srcQuery = style.src ? `&src` : `` |
| 255 | + const query = `?vue&type=style&index=${i}${srcQuery}` |
| 256 | + const styleRequest = src + query + attrsQuery |
| 257 | + if (style.module) { |
| 258 | + if (!hasCSSModules) { |
| 259 | + stylesCode += `\nconst cssModules = _sfc_main.__cssModules = {}` |
| 260 | + hasCSSModules = true |
| 261 | + } |
| 262 | + stylesCode += genCSSModulesCode(i, styleRequest, style.module) |
| 263 | + } else { |
| 264 | + stylesCode += `\nimport ${JSON.stringify(styleRequest)}` |
| 265 | + } |
| 266 | + // TODO SSR critical CSS collection |
| 267 | + }) |
| 268 | + } |
| 269 | + return stylesCode |
| 270 | +} |
| 271 | + |
| 272 | +function genCustomBlockCode(descriptor: SFCDescriptor) { |
| 273 | + let code = '' |
| 274 | + descriptor.customBlocks.forEach((block, index) => { |
| 275 | + const src = block.src || descriptor.filename |
| 276 | + const attrsQuery = attrsToQuery(block.attrs, block.type) |
| 277 | + const srcQuery = block.src ? `&src` : `` |
| 278 | + const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}` |
| 279 | + const request = JSON.stringify(src + query) |
| 280 | + code += `import block${index} from ${request}\n` |
| 281 | + code += `if (typeof block${index} === 'function') block${index}(_sfc_main)\n` |
| 282 | + }) |
| 283 | + return code |
| 284 | +} |
| 285 | + |
| 286 | +function genCSSModulesCode( |
| 287 | + index: number, |
| 288 | + request: string, |
| 289 | + moduleName: string | boolean |
| 290 | +): string { |
| 291 | + const styleVar = `style${index}` |
| 292 | + const exposedName = typeof moduleName === 'string' ? moduleName : '$style' |
| 293 | + // inject `.module` before extension so vite handles it as css module |
| 294 | + const moduleRequest = request.replace(/\.(\w+)$/, '.module.$1') |
| 295 | + return ( |
| 296 | + `\nimport ${styleVar} from ${JSON.stringify(moduleRequest)}` + |
| 297 | + `\ncssModules["${exposedName}"] = ${styleVar}` |
| 298 | + ) |
| 299 | +} |
| 300 | + |
| 301 | +// these are built-in query parameters so should be ignored |
| 302 | +// if the user happen to add them as attrs |
| 303 | +const ignoreList = ['id', 'index', 'src', 'type', 'lang', 'module'] |
| 304 | + |
| 305 | +function attrsToQuery( |
| 306 | + attrs: SFCBlock['attrs'], |
| 307 | + langFallback?: string, |
| 308 | + forceLangFallback = false |
| 309 | +): string { |
| 310 | + let query = `` |
| 311 | + for (const name in attrs) { |
| 312 | + const value = attrs[name] |
| 313 | + if (!ignoreList.includes(name)) { |
| 314 | + query += `&${qs.escape(name)}${ |
| 315 | + value ? `=${qs.escape(String(value))}` : `` |
| 316 | + }` |
| 317 | + } |
| 318 | + } |
| 319 | + if (langFallback || attrs.lang) { |
| 320 | + query += |
| 321 | + `lang` in attrs |
| 322 | + ? forceLangFallback |
| 323 | + ? `&lang.${langFallback}` |
| 324 | + : `&lang.${attrs.lang}` |
| 325 | + : `&lang.${langFallback}` |
| 326 | + } |
| 327 | + return query |
| 328 | +} |
0 commit comments