pagesJson.ts 8.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import path from 'path'
fxy060608's avatar
fxy060608 已提交
2
import type { Plugin, ResolvedConfig } from 'vite'
fxy060608's avatar
fxy060608 已提交
3
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,
14 15
  isEnableTreeShaking,
  parseManifestJsonOnce,
fxy060608's avatar
fxy060608 已提交
16 17 18
} from '@dcloudio/uni-cli-shared'

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, useI18n, setupWindow, setupPage } from '@dcloudio/uni-h5'
Q
qiang 已提交
58
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, googleMapKey, nvue, locale, fallbackLocale } from '${manifestJsonPath}'
fxy060608's avatar
fxy060608 已提交
59
const locales = import.meta.globEager('./locale/*.json')
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
${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 已提交
81
// 兼容 wx 对象
fxy060608's avatar
fxy060608 已提交
82 83
function registerGlobalCode(config: ResolvedConfig, ssr?: boolean) {
  const name = getGlobal(ssr)
84 85 86 87 88
  const enableTreeShaking = isEnableTreeShaking(
    parseManifestJsonOnce(process.env.UNI_INPUT_DIR)
  )
  if (enableTreeShaking && config.command === 'build' && !ssr) {
    // 非 SSR 的发行模式,补充全局 uni 对象
fxy060608's avatar
fxy060608 已提交
89
    return `${name}.uni = {};${name}.wx = {}`
fxy060608's avatar
fxy060608 已提交
90 91
  }

fxy060608's avatar
fxy060608 已提交
92 93 94 95 96 97 98 99 100 101
  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 已提交
102
${name}.wx = uni
fxy060608's avatar
fxy060608 已提交
103 104 105 106 107 108 109 110 111
${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 已提交
112 113 114
  if (config.isProduction) {
    cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'shadow.css')
  }
fxy060608's avatar
fxy060608 已提交
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 150 151 152 153
  // 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 已提交
154 155 156 157 158
  const windowNames = {
    topWindow: -1,
    leftWindow: -2,
    rightWindow: -3,
  }
fxy060608's avatar
fxy060608 已提交
159 160
  let importLayoutComponentsCode = ''
  let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`
fxy060608's avatar
fxy060608 已提交
161 162
  Object.keys(windowNames).forEach((name) => {
    const windowConfig = pagesJson[name as keyof typeof windowNames]
fxy060608's avatar
fxy060608 已提交
163 164
    if (windowConfig && windowConfig.path) {
      importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`
fxy060608's avatar
fxy060608 已提交
165 166 167
      defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = setupWindow(${name},${
        windowNames[name as keyof typeof windowNames]
      })\n`
fxy060608's avatar
fxy060608 已提交
168 169 170 171 172 173 174 175 176 177
    }
  })

  return {
    importLayoutComponentsCode,
    defineLayoutComponentsCode,
  }
}

function generatePageDefineCode(pageOptions: UniApp.PagesJsonPageOptions) {
fxy060608's avatar
fxy060608 已提交
178
  let pagePathWithExtname = normalizePagePath(pageOptions.path, 'h5')
fxy060608's avatar
fxy060608 已提交
179
  if (!pagePathWithExtname) {
fxy060608's avatar
fxy060608 已提交
180 181
    // 不存在时,仍引用,此时编译会报错文件不存在
    pagePathWithExtname = pageOptions.path + '.vue'
fxy060608's avatar
fxy060608 已提交
182
  }
fxy060608's avatar
fxy060608 已提交
183
  const pageIdent = normalizeIdentifier(pageOptions.path)
fxy060608's avatar
fxy060608 已提交
184
  return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}').then(com => setupPage(com.default || com))
fxy060608's avatar
fxy060608 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
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 已提交
206
  { path, meta }: UniApp.UniRoute,
fxy060608's avatar
fxy060608 已提交
207
  _config: ResolvedConfig
fxy060608's avatar
fxy060608 已提交
208 209 210 211 212
) {
  const { isEntry } = meta
  const alias = isEntry ? `\n  alias:'/${path}',` : ''
  return `{
  path:'/${isEntry ? '' : path}',${alias}
fxy060608's avatar
fxy060608 已提交
213
  component:{setup(){return ()=>renderPage(${normalizeIdentifier(path)})}},
fxy060608's avatar
fxy060608 已提交
214
  loader: ${normalizeIdentifier(path)}Loader,
fxy060608's avatar
fxy060608 已提交
215 216 217 218 219
  meta: ${JSON.stringify(meta)}
}`
}

function generatePagesRoute(
fxy060608's avatar
fxy060608 已提交
220
  pagesRouteOptions: UniApp.UniRoute[],
fxy060608's avatar
fxy060608 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  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 已提交
239 240 241
  ].join(
    ','
  )}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).substr(1),uniRoute))`
fxy060608's avatar
fxy060608 已提交
242 243 244 245 246 247 248 249 250 251
}

function generateConfig(
  globalName: string,
  pagesJson: Record<string, any>,
  config: ResolvedConfig
) {
  delete pagesJson.pages
  delete pagesJson.subPackages
  delete pagesJson.subpackages
fxy060608's avatar
fxy060608 已提交
252
  pagesJson.compilerVersion = process.env.UNI_COMPILER_VERSION
fxy060608's avatar
fxy060608 已提交
253 254 255 256 257 258 259 260 261 262 263 264
  return (
    (config.command === 'serve'
      ? ''
      : `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
    `${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
  async,
  debug,
  networkTimeout,
  sdkConfigs,
  qqMapKey,
Q
qiang 已提交
265
  googleMapKey,
fxy060608's avatar
fxy060608 已提交
266
  nvue,
Q
qiang 已提交
267
  locale,
fxy060608's avatar
fxy060608 已提交
268
  fallbackLocale,
269
  locales:Object.keys(locales).reduce((res,name)=>{const locale=name.replace(/\\.\\/locale\\/(uni-app.)?(.*).json/,'$2');extend(res[locale]||(res[locale]={}),locales[name].default);return res},{}),
fxy060608's avatar
fxy060608 已提交
270
  router,
fxy060608's avatar
fxy060608 已提交
271 272 273 274
})
`
  )
}