ssr.ts 5.1 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 16
import { ConfigEnv, ResolvedConfig, UserConfig } from 'vite'
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 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

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

export function rewriteSsrVue(mode?: 2 | 3) {
  // 解决 @vue/server-renderer 中引入 vue 的映射
  let vuePath: string
  if (mode === 2) {
    vuePath = resolveBuiltIn(
      '@dcloudio/uni-h5-vue/dist/vue.runtime.compat.cjs.js'
    )
  } else {
    vuePath = resolveBuiltIn('@dcloudio/uni-h5-vue/dist/vue.runtime.cjs.js')
  }
  require('module-alias').addAlias('vue', vuePath)
}

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

export function rewriteSsrResolve(mode?: 2 | 3) {
  // 解决 ssr 时 __vite_ssr_import__("vue") 的映射
fxy060608's avatar
fxy060608 已提交
120 121 122 123 124
  const resolve = require(require.resolve('resolve', {
    paths: [
      path.resolve(require.resolve('vite/package.json'), '../node_modules'),
    ],
  }))
fxy060608's avatar
fxy060608 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138
  const oldSync = resolve.sync
  resolve.sync = (id: string, opts?: resolve.SyncOpts) => {
    if (id === 'vue') {
      return resolveBuiltIn(
        `@dcloudio/uni-h5-vue/dist/vue.runtime.${
          mode === 2 ? 'compat.' : ''
        }cjs.js`
      )
    }
    return oldSync(id, initResolveSyncOpts(opts))
  }
}

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

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