ssr.ts 5.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import path from 'path'
import fs from 'fs-extra'
import { extend, isArray, isString, NormalizedStyle } from '@vue/shared'
import {
fxy060608's avatar
fxy060608 已提交
5
  isH5NativeTag,
fxy060608's avatar
fxy060608 已提交
6 7 8
  createRpx2Unit,
  Rpx2UnitOptions,
} from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
9 10 11 12
import {
  parseRpx2UnitOnce,
  resolveBuiltIn,
  getBuiltInPaths,
fxy060608's avatar
fxy060608 已提交
13
  transformMatchMedia,
fxy060608's avatar
fxy060608 已提交
14
  normalizePath,
15
  transformH5BuiltInComponents,
fxy060608's avatar
fxy060608 已提交
16
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
17
import type { ConfigEnv, ResolvedConfig, UserConfig } from 'vite'
fxy060608's avatar
fxy060608 已提交
18
import resolve from 'resolve'
fxy060608's avatar
fxy060608 已提交
19 20
import { resolveComponentType } from '@vue/compiler-dom'
import { transformPageHead } from '../plugin/transforms/transformPageHead'
fxy060608's avatar
fxy060608 已提交
21

22 23 24 25
// Temporal handling for 2.7 breaking change
export const isSSR = (opt: { ssr?: boolean } | boolean | undefined) =>
  opt === undefined ? false : typeof opt === 'boolean' ? opt : opt?.ssr === true

fxy060608's avatar
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
export function isSsrManifest(
  command: ConfigEnv['command'],
  config: UserConfig | ResolvedConfig
) {
  if (command === 'build') {
    return !!(config.build && config.build.ssrManifest)
  }
  return false
}

export function initSsrDefine(config: ResolvedConfig) {
  return extend(globalThis, {
    __IMPORT_META_ENV_BASE_URL__: config.env.BASE_URL,
  })
}

function serializeDefine(define: Record<string, any>): string {
  let res = `{`
  for (const key in define) {
    const val = define[key]
    res += `${JSON.stringify(key)}: ${
      typeof val === 'string' ? `(${val})` : JSON.stringify(val)
    }, `
  }
  return res + `}`
}

function normalizeSsrDefine(config: ResolvedConfig) {
  const defines = extend(
    {
      __IMPORT_META_ENV_BASE_URL__: JSON.stringify(config.env.BASE_URL),
    },
    config.define!
  )
  delete defines['import.meta.env.LEGACY']
  return defines
}
export function generateSsrDefineCode(
  config: ResolvedConfig,
  { unit, unitRatio, unitPrecision }: Rpx2UnitOptions
): string {
  return fs
    .readFileSync(path.join(__dirname, '../../lib/ssr/define.js'), 'utf8')
    .replace('__DEFINES__', serializeDefine(normalizeSsrDefine(config)))
    .replace('__UNIT__', JSON.stringify(unit))
    .replace('__UNIT_RATIO__', JSON.stringify(unitRatio))
    .replace('__UNIT_PRECISION__', JSON.stringify(unitPrecision))
}

export function generateSsrEntryServerCode() {
  return fs.readFileSync(
    path.join(__dirname, '../../lib/ssr/entry-server.js'),
    'utf8'
  )
}

82
export function rewriteSsrVue() {
fxy060608's avatar
fxy060608 已提交
83
  // 解决 @vue/server-renderer 中引入 vue 的映射
84 85 86 87
  require('module-alias').addAlias(
    'vue',
    resolveBuiltIn('@dcloudio/uni-h5-vue/dist/vue.runtime.cjs.js')
  )
fxy060608's avatar
fxy060608 已提交
88 89 90 91 92 93
  // TODO vite 2.7.0 版本会定制 require 的解析,解析后缓存的文件路径会被格式化,导致 windows 平台路径不一致,导致 cache 不生效
  if (require('os').platform() === 'win32') {
    require('vue')
    const vuePath = require.resolve('vue')
    require.cache[normalizePath(vuePath)] = require.cache[vuePath]
  }
fxy060608's avatar
fxy060608 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106
}

function initResolveSyncOpts(opts?: resolve.SyncOpts) {
  if (!opts) {
    opts = {}
  }
  if (!opts.paths) {
    opts.paths = []
  }
  if (isString(opts.paths)) {
    opts.paths = [opts.paths]
  }
  if (isArray(opts.paths)) {
fxy060608's avatar
fxy060608 已提交
107
    opts.paths.push(...getBuiltInPaths())
fxy060608's avatar
fxy060608 已提交
108 109 110 111
  }
  return opts
}

112
export function rewriteSsrResolve() {
fxy060608's avatar
fxy060608 已提交
113
  // 解决 ssr 时 __vite_ssr_import__("vue") 的映射
fxy060608's avatar
fxy060608 已提交
114 115 116 117 118
  const resolve = require(require.resolve('resolve', {
    paths: [
      path.resolve(require.resolve('vite/package.json'), '../node_modules'),
    ],
  }))
fxy060608's avatar
fxy060608 已提交
119 120 121
  const oldSync = resolve.sync
  resolve.sync = (id: string, opts?: resolve.SyncOpts) => {
    if (id === 'vue') {
122 123 124
      return resolveBuiltIn(`@dcloudio/uni-h5-vue/dist/vue.runtime.cjs.js`)
    } else if (id === 'vue/package.json') {
      return resolveBuiltIn(`@dcloudio/uni-h5-vue/package.json`)
125 126
    } else if (id === 'vue/server-renderer/package.json') {
      return resolveBuiltIn(`@vue/server-renderer/package.json`)
fxy060608's avatar
fxy060608 已提交
127 128 129 130 131 132
    }
    return oldSync(id, initResolveSyncOpts(opts))
  }
}

export function rewriteSsrNativeTag() {
fxy060608's avatar
fxy060608 已提交
133
  // @ts-ignore
fxy060608's avatar
fxy060608 已提交
134
  const compilerDom = require(resolveBuiltIn('@vue/compiler-dom'))
fxy060608's avatar
fxy060608 已提交
135 136
  // TODO compiler-ssr时,传入的 isNativeTag 会被 @vue/compiler-dom 的 isNativeTag 覆盖
  // https://github.com/vuejs/vue-next/blob/master/packages/compiler-ssr/src/index.ts#L36
fxy060608's avatar
fxy060608 已提交
137 138 139 140 141 142 143 144 145 146 147 148
  compilerDom.parserOptions.isNativeTag = isH5NativeTag

  // ssr 时,ssrTransformComponent 执行时机很早,导致无法正确重写 tag,故通过 resolveComponentType 解决重写
  const oldResolveComponentType =
    compilerDom.resolveComponentType as typeof resolveComponentType
  const newResolveComponentType: typeof resolveComponentType = function (
    node,
    context,
    ssr
  ) {
    transformPageHead(node, context)
    transformMatchMedia(node, context)
149
    transformH5BuiltInComponents(node, context)
fxy060608's avatar
fxy060608 已提交
150 151 152
    return oldResolveComponentType(node, context, ssr)
  }
  compilerDom.resolveComponentType = newResolveComponentType
fxy060608's avatar
fxy060608 已提交
153 154 155
}

export function rewriteSsrRenderStyle(inputDir: string) {
fxy060608's avatar
fxy060608 已提交
156
  const { unit, unitRatio, unitPrecision } = parseRpx2UnitOnce(inputDir, 'h5')
fxy060608's avatar
fxy060608 已提交
157 158 159 160 161 162 163 164 165 166 167
  const rpx2unit = createRpx2Unit(unit, unitRatio, unitPrecision)
  const shared = require('@vue/shared')
  const oldStringifyStyle = shared.stringifyStyle
  shared.stringifyStyle = (styles: NormalizedStyle | undefined) =>
    rpx2unit(oldStringifyStyle(styles))
  const serverRender = require('@vue/server-renderer')
  const oldSsrRenderStyle = serverRender.ssrRenderStyle
  // 仅对字符串类型做转换,非字符串类型,通过 stringifyStyle 转换
  serverRender.ssrRenderStyle = (raw: unknown) =>
    isString(raw) ? rpx2unit(oldSsrRenderStyle(raw)) : oldSsrRenderStyle(raw)
}