pagesJson.ts 8.1 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
} from '@dcloudio/uni-cli-shared'

export function uniPagesJsonPlugin(): Plugin {
fxy060608's avatar
fxy060608 已提交
17 18 19 20 21 22 23 24 25
  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 已提交
26 27
              registerGlobalCode(resolvedConfig, ssr) +
              generatePagesJsonCode(ssr, code, resolvedConfig),
fxy060608's avatar
fxy060608 已提交
28 29
            map: { mappings: '' },
          }
fxy060608's avatar
fxy060608 已提交
30
        }
fxy060608's avatar
fxy060608 已提交
31 32 33
      },
    }
  })
fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41
}

function generatePagesJsonCode(
  ssr: boolean | undefined,
  jsonStr: string,
  config: ResolvedConfig
) {
  const globalName = getGlobal(ssr)
fxy060608's avatar
fxy060608 已提交
42
  const pagesJson = normalizePagesJson(jsonStr, process.env.UNI_PLATFORM)
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47
  const { importLayoutComponentsCode, defineLayoutComponentsCode } =
    generateLayoutComponentsCode(globalName, pagesJson)
  const definePagesCode = generatePagesDefineCode(pagesJson, config)
  const uniRoutesCode = generateRoutes(globalName, pagesJson, config)
  const uniConfigCode = generateConfig(globalName, pagesJson, config)
48
  const manifestJsonPath = normalizePath(
fxy060608's avatar
fxy060608 已提交
49 50 51 52 53 54
    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 已提交
55
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent, useI18n, setupWindow } from '@dcloudio/uni-h5'
Q
qiang 已提交
56
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, googleMapKey, nvue, locale, fallbackLocale } from '${manifestJsonPath}'
fxy060608's avatar
fxy060608 已提交
57
const locales = import.meta.globEager('./locale/*.json')
fxy060608's avatar
fxy060608 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
${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 已提交
79
// 兼容 wx 对象
fxy060608's avatar
fxy060608 已提交
80 81
function registerGlobalCode(config: ResolvedConfig, ssr?: boolean) {
  const name = getGlobal(ssr)
fxy060608's avatar
fxy060608 已提交
82 83
  if (config.command === 'build' && !ssr) {
    // 非SSR的发行模式,补充全局 uni 对象
fxy060608's avatar
fxy060608 已提交
84
    return `${name}.uni = {};${name}.wx = {}`
fxy060608's avatar
fxy060608 已提交
85 86
  }

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

  return {
    importLayoutComponentsCode,
    defineLayoutComponentsCode,
  }
}

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

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

function generateConfig(
  globalName: string,
  pagesJson: Record<string, any>,
  config: ResolvedConfig
) {
  delete pagesJson.pages
  delete pagesJson.subPackages
  delete pagesJson.subpackages
fxy060608's avatar
fxy060608 已提交
247
  pagesJson.compilerVersion = process.env.UNI_COMPILER_VERSION
fxy060608's avatar
fxy060608 已提交
248 249 250 251 252 253 254 255 256 257 258 259
  return (
    (config.command === 'serve'
      ? ''
      : `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
    `${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
  async,
  debug,
  networkTimeout,
  sdkConfigs,
  qqMapKey,
Q
qiang 已提交
260
  googleMapKey,
fxy060608's avatar
fxy060608 已提交
261
  nvue,
Q
qiang 已提交
262
  locale,
fxy060608's avatar
fxy060608 已提交
263
  fallbackLocale,
264
  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 已提交
265
  router,
fxy060608's avatar
fxy060608 已提交
266 267 268 269
})
`
  )
}