pagesJson.ts 7.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3
import path from 'path'
import { Plugin, ResolvedConfig } from 'vite'
import {
fxy060608's avatar
fxy060608 已提交
4
  API_DEPS_CSS,
fxy060608's avatar
fxy060608 已提交
5 6 7
  FEATURE_DEFINES,
  H5_FRAMEWORK_STYLE_PATH,
  BASE_COMPONENTS_STYLE_PATH,
fxy060608's avatar
fxy060608 已提交
8
  normalizeIdentifier,
fxy060608's avatar
fxy060608 已提交
9
  normalizePagesJson,
fxy060608's avatar
fxy060608 已提交
10
  defineUniPagesJsonPlugin,
fxy060608's avatar
fxy060608 已提交
11
  normalizePagesRoute,
fxy060608's avatar
fxy060608 已提交
12
  normalizePagePath,
13
  normalizePath,
fxy060608's avatar
fxy060608 已提交
14 15 16 17 18
} from '@dcloudio/uni-cli-shared'

const pkg = require('@dcloudio/vite-plugin-uni/package.json')

export function uniPagesJsonPlugin(): Plugin {
fxy060608's avatar
fxy060608 已提交
19 20 21 22 23 24 25 26 27
  return defineUniPagesJsonPlugin((opts) => {
    return {
      name: 'vite:uni-h5-pages-json',
      enforce: 'pre',
      transform(code, id, ssr) {
        if (opts.filter(id)) {
          const { resolvedConfig } = opts
          return {
            code:
fxy060608's avatar
fxy060608 已提交
28 29
              registerGlobalCode(resolvedConfig, ssr) +
              generatePagesJsonCode(ssr, code, resolvedConfig),
fxy060608's avatar
fxy060608 已提交
30 31
            map: { mappings: '' },
          }
fxy060608's avatar
fxy060608 已提交
32
        }
fxy060608's avatar
fxy060608 已提交
33 34 35
      },
    }
  })
fxy060608's avatar
fxy060608 已提交
36 37 38 39 40 41 42 43
}

function generatePagesJsonCode(
  ssr: boolean | undefined,
  jsonStr: string,
  config: ResolvedConfig
) {
  const globalName = getGlobal(ssr)
fxy060608's avatar
fxy060608 已提交
44
  const pagesJson = normalizePagesJson(jsonStr, process.env.UNI_PLATFORM)
fxy060608's avatar
fxy060608 已提交
45 46 47 48 49
  const { importLayoutComponentsCode, defineLayoutComponentsCode } =
    generateLayoutComponentsCode(globalName, pagesJson)
  const definePagesCode = generatePagesDefineCode(pagesJson, config)
  const uniRoutesCode = generateRoutes(globalName, pagesJson, config)
  const uniConfigCode = generateConfig(globalName, pagesJson, config)
50
  const manifestJsonPath = normalizePath(
fxy060608's avatar
fxy060608 已提交
51 52 53 54 55 56
    path.resolve(process.env.UNI_INPUT_DIR, 'manifest.json.js')
  )
  const cssCode = generateCssCode(config)

  return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
fxy060608's avatar
fxy060608 已提交
57
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent, setupWindow } from '@dcloudio/uni-h5'
Q
qiang 已提交
58
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue, locale } from '${manifestJsonPath}'
fxy060608's avatar
fxy060608 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${config.command === 'serve' ? hmrCode : ''}
export {}
`
}

const hmrCode = `if(import.meta.hot){
  import.meta.hot.on('invalidate', (data) => {
      import.meta.hot.invalidate()
  })
}`

function getGlobal(ssr?: boolean) {
  return ssr ? 'global' : 'window'
}
fxy060608's avatar
fxy060608 已提交
80
// 兼容 wx 对象
fxy060608's avatar
fxy060608 已提交
81 82
function registerGlobalCode(config: ResolvedConfig, ssr?: boolean) {
  const name = getGlobal(ssr)
fxy060608's avatar
fxy060608 已提交
83 84
  if (config.command === 'build' && !ssr) {
    // 非SSR的发行模式,补充全局 uni 对象
fxy060608's avatar
fxy060608 已提交
85
    return `${name}.uni = {};${name}.wx = {}`
fxy060608's avatar
fxy060608 已提交
86 87
  }

fxy060608's avatar
fxy060608 已提交
88 89 90 91 92 93 94 95 96 97
  const rpx2pxCode =
    !ssr && config.define!.__UNI_FEATURE_RPX__
      ? `import {upx2px} from '@dcloudio/uni-h5'
  ${name}.rpx2px = upx2px
`
      : ''
  return `${rpx2pxCode}
import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
fxy060608's avatar
fxy060608 已提交
98
${name}.wx = uni
fxy060608's avatar
fxy060608 已提交
99 100 101 102 103 104 105 106 107
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
`
}

function generateCssCode(config: ResolvedConfig) {
  const define = config.define! as FEATURE_DEFINES
  const cssFiles = [H5_FRAMEWORK_STYLE_PATH + 'base.css']
fxy060608's avatar
fxy060608 已提交
108 109 110
  if (config.isProduction) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'shadow.css')
  }
fxy060608's avatar
fxy060608 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  // if (define.__UNI_FEATURE_PAGES__) {
  cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'async.css')
  // }
  if (define.__UNI_FEATURE_RESPONSIVE__) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'layout.css')
  }
  if (define.__UNI_FEATURE_NAVIGATIONBAR__) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'pageHead.css')
  }
  if (define.__UNI_FEATURE_TABBAR__) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'tabBar.css')
  }
  if (define.__UNI_FEATURE_NVUE__) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'nvue.css')
  }
  if (define.__UNI_FEATURE_PULL_DOWN_REFRESH__) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'pageRefresh.css')
  }
  if (define.__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__) {
    cssFiles.push(BASE_COMPONENTS_STYLE_PATH + 'input.css')
  }
  if (config.command === 'serve') {
    // 开发模式,自动添加所有API相关css
    Object.keys(API_DEPS_CSS).forEach((name) => {
      const styles = API_DEPS_CSS[name as keyof typeof API_DEPS_CSS]
      styles.forEach((style) => {
        if (!cssFiles.includes(style)) {
          cssFiles.push(style)
        }
      })
    })
  }
  return cssFiles.map((file) => `import '${file}'`).join('\n')
}

function generateLayoutComponentsCode(
  globalName: string,
  pagesJson: UniApp.PagesJson
) {
fxy060608's avatar
fxy060608 已提交
150 151 152 153 154
  const windowNames = {
    topWindow: -1,
    leftWindow: -2,
    rightWindow: -3,
  }
fxy060608's avatar
fxy060608 已提交
155 156
  let importLayoutComponentsCode = ''
  let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`
fxy060608's avatar
fxy060608 已提交
157 158
  Object.keys(windowNames).forEach((name) => {
    const windowConfig = pagesJson[name as keyof typeof windowNames]
fxy060608's avatar
fxy060608 已提交
159 160
    if (windowConfig && windowConfig.path) {
      importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`
fxy060608's avatar
fxy060608 已提交
161 162 163
      defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = setupWindow(${name},${
        windowNames[name as keyof typeof windowNames]
      })\n`
fxy060608's avatar
fxy060608 已提交
164 165 166 167 168 169 170 171 172 173
    }
  })

  return {
    importLayoutComponentsCode,
    defineLayoutComponentsCode,
  }
}

function generatePageDefineCode(pageOptions: UniApp.PagesJsonPageOptions) {
fxy060608's avatar
fxy060608 已提交
174
  let pagePathWithExtname = normalizePagePath(pageOptions.path, 'h5')
fxy060608's avatar
fxy060608 已提交
175
  if (!pagePathWithExtname) {
fxy060608's avatar
fxy060608 已提交
176 177
    // 不存在时,仍引用,此时编译会报错文件不存在
    pagePathWithExtname = pageOptions.path + '.vue'
fxy060608's avatar
fxy060608 已提交
178
  }
fxy060608's avatar
fxy060608 已提交
179
  const pageIdent = normalizeIdentifier(pageOptions.path)
fxy060608's avatar
fxy060608 已提交
180
  return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}?mpType=page')
fxy060608's avatar
fxy060608 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`
}

function generatePagesDefineCode(
  pagesJson: UniApp.PagesJson,
  _config: ResolvedConfig
) {
  const { pages } = pagesJson
  return (
    `const AsyncComponentOptions = {
  loadingComponent: AsyncLoadingComponent,
  errorComponent: AsyncErrorComponent,
  delay: async.delay,
  timeout: async.timeout,
  suspensible: async.suspensible
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n')
  )
}

function generatePageRoute(
fxy060608's avatar
fxy060608 已提交
202
  { path, meta }: UniApp.UniRoute,
fxy060608's avatar
fxy060608 已提交
203
  _config: ResolvedConfig
fxy060608's avatar
fxy060608 已提交
204 205 206 207 208
) {
  const { isEntry } = meta
  const alias = isEntry ? `\n  alias:'/${path}',` : ''
  return `{
  path:'/${isEntry ? '' : path}',${alias}
fxy060608's avatar
fxy060608 已提交
209
  component:{setup(){return ()=>renderPage(${normalizeIdentifier(path)})}},
fxy060608's avatar
fxy060608 已提交
210
  loader: ${normalizeIdentifier(path)}Loader,
fxy060608's avatar
fxy060608 已提交
211 212 213 214 215
  meta: ${JSON.stringify(meta)}
}`
}

function generatePagesRoute(
fxy060608's avatar
fxy060608 已提交
216
  pagesRouteOptions: UniApp.UniRoute[],
fxy060608's avatar
fxy060608 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  config: ResolvedConfig
) {
  return pagesRouteOptions.map((pageOptions) =>
    generatePageRoute(pageOptions, config)
  )
}

function generateRoutes(
  globalName: string,
  pagesJson: UniApp.PagesJson,
  config: ResolvedConfig
) {
  return `
function renderPage(component){
  return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, { ref: "page" }, null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
    ...generatePagesRoute(normalizePagesRoute(pagesJson), config),
fxy060608's avatar
fxy060608 已提交
235 236 237
  ].join(
    ','
  )}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).substr(1),uniRoute))`
fxy060608's avatar
fxy060608 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
}

function generateConfig(
  globalName: string,
  pagesJson: Record<string, any>,
  config: ResolvedConfig
) {
  delete pagesJson.pages
  delete pagesJson.subPackages
  delete pagesJson.subpackages
  pagesJson.compilerVersion = pkg['uni-app'].compilerVersion
  return (
    (config.command === 'serve'
      ? ''
      : `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
    `${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
  async,
  debug,
  networkTimeout,
  sdkConfigs,
  qqMapKey,
  nvue,
Q
qiang 已提交
262
  locale,
fxy060608's avatar
fxy060608 已提交
263 264 265 266 267
  router
})
`
  )
}