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

21 22 23 24
// 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 已提交
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 93
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'
  )
}

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

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 已提交
119
    opts.paths.push(...getBuiltInPaths())
fxy060608's avatar
fxy060608 已提交
120 121 122 123
  }
  return opts
}

124
export function rewriteSsrResolve() {
fxy060608's avatar
fxy060608 已提交
125
  // 解决 ssr 时 __vite_ssr_import__("vue") 的映射
fxy060608's avatar
fxy060608 已提交
126 127 128 129 130
  const resolve = require(require.resolve('resolve', {
    paths: [
      path.resolve(require.resolve('vite/package.json'), '../node_modules'),
    ],
  }))
fxy060608's avatar
fxy060608 已提交
131 132 133
  const oldSync = resolve.sync
  resolve.sync = (id: string, opts?: resolve.SyncOpts) => {
    if (id === 'vue') {
134 135 136
      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`)
137 138
    } else if (id === 'vue/server-renderer/package.json') {
      return resolveBuiltIn(`@vue/server-renderer/package.json`)
fxy060608's avatar
fxy060608 已提交
139 140 141 142 143 144
    }
    return oldSync(id, initResolveSyncOpts(opts))
  }
}

export function rewriteSsrNativeTag() {
fxy060608's avatar
fxy060608 已提交
145
  // @ts-ignore
fxy060608's avatar
fxy060608 已提交
146
  const compilerDom = require(resolveBuiltIn('@vue/compiler-dom'))
fxy060608's avatar
fxy060608 已提交
147 148
  // 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 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  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 已提交
164 165 166
}

export function rewriteSsrRenderStyle(inputDir: string) {
fxy060608's avatar
fxy060608 已提交
167
  const { unit, unitRatio, unitPrecision } = parseRpx2UnitOnce(inputDir, 'h5')
fxy060608's avatar
fxy060608 已提交
168 169 170 171 172 173 174 175 176 177 178
  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)
}