ssr.ts 5.2 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
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
15
import type { ConfigEnv, ResolvedConfig, UserConfig } from 'vite'
fxy060608's avatar
fxy060608 已提交
16
import resolve from 'resolve'
fxy060608's avatar
fxy060608 已提交
17 18
import { resolveComponentType } from '@vue/compiler-dom'
import { transformPageHead } from '../plugin/transforms/transformPageHead'
fxy060608's avatar
fxy060608 已提交
19

20 21 22 23
// 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 已提交
24 25 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 82 83 84 85 86 87 88 89 90 91 92
export function isSsr(
  command: ConfigEnv['command'],
  config: UserConfig | ResolvedConfig
) {
  if (command === 'serve') {
    return !!(config.server && config.server.middlewareMode)
  }
  if (command === 'build') {
    return !!(config.build && config.build.ssr)
  }
  return false
}

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'
  )
}

93
export function rewriteSsrVue() {
fxy060608's avatar
fxy060608 已提交
94
  // 解决 @vue/server-renderer 中引入 vue 的映射
95 96 97 98
  require('module-alias').addAlias(
    'vue',
    resolveBuiltIn('@dcloudio/uni-h5-vue/dist/vue.runtime.cjs.js')
  )
fxy060608's avatar
fxy060608 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111
}

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 已提交
112
    opts.paths.push(...getBuiltInPaths())
fxy060608's avatar
fxy060608 已提交
113 114 115 116
  }
  return opts
}

117
export function rewriteSsrResolve() {
fxy060608's avatar
fxy060608 已提交
118
  // 解决 ssr 时 __vite_ssr_import__("vue") 的映射
fxy060608's avatar
fxy060608 已提交
119 120 121 122 123
  const resolve = require(require.resolve('resolve', {
    paths: [
      path.resolve(require.resolve('vite/package.json'), '../node_modules'),
    ],
  }))
fxy060608's avatar
fxy060608 已提交
124 125 126
  const oldSync = resolve.sync
  resolve.sync = (id: string, opts?: resolve.SyncOpts) => {
    if (id === 'vue') {
127 128 129
      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`)
fxy060608's avatar
fxy060608 已提交
130 131 132 133 134 135
    }
    return oldSync(id, initResolveSyncOpts(opts))
  }
}

export function rewriteSsrNativeTag() {
fxy060608's avatar
fxy060608 已提交
136
  // @ts-ignore
fxy060608's avatar
fxy060608 已提交
137
  const compilerDom = require(resolveBuiltIn('@vue/compiler-dom'))
fxy060608's avatar
fxy060608 已提交
138 139
  // 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 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  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)
    return oldResolveComponentType(node, context, ssr)
  }
  compilerDom.resolveComponentType = newResolveComponentType
fxy060608's avatar
fxy060608 已提交
155 156 157
}

export function rewriteSsrRenderStyle(inputDir: string) {
fxy060608's avatar
fxy060608 已提交
158
  const { unit, unitRatio, unitPrecision } = parseRpx2UnitOnce(inputDir, 'h5')
fxy060608's avatar
fxy060608 已提交
159 160 161 162 163 164 165 166 167 168 169
  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)
}