pagesJson.ts 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7
import path from 'path'
import { Plugin } from 'vite'

import {
  defineUniPagesJsonPlugin,
  normalizePagesJson,
  getLocaleFiles,
fxy060608's avatar
fxy060608 已提交
8
  normalizePagePath,
fxy060608's avatar
fxy060608 已提交
9
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
10
import { virtualPagePath } from './virtual'
fxy060608's avatar
fxy060608 已提交
11
import { UniMiniProgramPluginOptions } from '../plugin'
fxy060608's avatar
fxy060608 已提交
12

fxy060608's avatar
fxy060608 已提交
13 14 15
export function uniPagesJsonPlugin(
  options: UniMiniProgramPluginOptions
): Plugin {
fxy060608's avatar
fxy060608 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  let pagesJson: UniApp.PagesJson
  return defineUniPagesJsonPlugin((opts) => {
    return {
      name: 'vite:uni-mp-pages-json',
      enforce: 'pre',
      transform(code, id) {
        if (!opts.filter(id)) {
          return
        }
        this.addWatchFile(path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'))
        getLocaleFiles(
          path.resolve(process.env.UNI_INPUT_DIR, 'locale')
        ).forEach((filepath) => {
          this.addWatchFile(filepath)
        })
        pagesJson = normalizePagesJson(code, process.env.UNI_PLATFORM)
        // TODO subpackages
        pagesJson.pages.forEach((page) => {
          this.addWatchFile(
            path.resolve(process.env.UNI_INPUT_DIR, page.path + '.vue')
          )
        })
        return {
          code:
fxy060608's avatar
fxy060608 已提交
40 41
            `import './manifest.json.js'\n` +
            normalizeMiniProgramPagesJson(pagesJson),
fxy060608's avatar
fxy060608 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
          map: this.getCombinedSourcemap(),
        }
      },
      generateBundle() {
        // this.emitFile({
        //   fileName: `app-config-service.js`,
        //   type: 'asset',
        //   source: normalizeAppConfigService(
        //     pagesJson,
        //     parseManifestJsonOnce(process.env.UNI_INPUT_DIR)
        //   ),
        // })
      },
    }
  })
}
fxy060608's avatar
fxy060608 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71

function normalizeMiniProgramPagesJson(pagesJson: Record<string, any>) {
  const importPagesCode: string[] = []
  pagesJson.pages.forEach((page: UniApp.PagesJsonPageOptions) => {
    const pagePath = page.path
    const pagePathWithExtname = normalizePagePath(pagePath, 'app')
    if (pagePathWithExtname) {
      importPagesCode.push(`import('${virtualPagePath(pagePathWithExtname)}')`)
    }
  })
  return `if(!Math){
${importPagesCode.join('\n')}
}`
}