mainJs.ts 1.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import path from 'path'
import slash from 'slash'
fxy060608's avatar
fxy060608 已提交
3
import { Plugin, ResolvedConfig } from 'vite'
fxy060608's avatar
fxy060608 已提交
4
import { VitePluginUniResolvedOptions } from '../..'
fxy060608's avatar
fxy060608 已提交
5
import { isSsr, isSsrManifest } from '../../utils'
fxy060608's avatar
fxy060608 已提交
6

fxy060608's avatar
fxy060608 已提交
7 8 9 10
export function uniMainJsPlugin(
  config: ResolvedConfig,
  options: VitePluginUniResolvedOptions
): Plugin {
fxy060608's avatar
fxy060608 已提交
11 12 13 14
  const mainPath = slash(path.resolve(options.inputDir, 'main'))
  const mainJsPath = mainPath + '.js'
  const mainTsPath = mainPath + '.ts'
  const pagesJsonJsPath = slash(path.resolve(options.inputDir, 'pages.json.js'))
fxy060608's avatar
fxy060608 已提交
15
  const isSSR =
fxy060608's avatar
fxy060608 已提交
16
    isSsr(config.command, config) || isSsrManifest(config.command, config)
fxy060608's avatar
fxy060608 已提交
17 18
  return {
    name: 'vite:uni-main-js',
fxy060608's avatar
fxy060608 已提交
19
    transform(code, id, ssr) {
fxy060608's avatar
fxy060608 已提交
20
      if (id === mainJsPath || id === mainTsPath) {
fxy060608's avatar
fxy060608 已提交
21
        if (!isSSR) {
22 23 24
          code = code.includes('createSSRApp')
            ? createApp(code)
            : createLegacyApp(code)
fxy060608's avatar
fxy060608 已提交
25
        } else {
fxy060608's avatar
fxy060608 已提交
26
          code = ssr ? createSSRServerApp(code) : createSSRClientApp(code)
fxy060608's avatar
fxy060608 已提交
27
        }
fxy060608's avatar
fxy060608 已提交
28
        return {
fxy060608's avatar
fxy060608 已提交
29
          code: `import { plugin } from '@dcloudio/uni-h5';import '${pagesJsonJsPath}';${code}`,
fxy060608's avatar
fxy060608 已提交
30 31 32 33 34 35
          map: this.getCombinedSourcemap(),
        }
      }
    },
  }
}
fxy060608's avatar
fxy060608 已提交
36 37

function createApp(code: string) {
38 39 40 41 42 43 44
  return `createApp().app.use(plugin).mount("#app");${code.replace(
    'createSSRApp',
    'createVueApp as createSSRApp'
  )}`
}

function createLegacyApp(code: string) {
fxy060608's avatar
fxy060608 已提交
45 46 47 48 49 50 51
  return `function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(plugin)};${code.replace(
    'createApp',
    'createVueApp'
  )}`
}

function createSSRClientApp(code: string) {
52
  return `import { UNI_SSR, UNI_SSR_STORE } from '@dcloudio/uni-shared';const { app, store } = createApp();app.use(plugin);store && window[UNI_SSR] && window[UNI_SSR][UNI_SSR_STORE] && store.replaceState(window[UNI_SSR][UNI_SSR_STORE]);app.router.isReady().then(() => app.mount("#app"));${code}`
fxy060608's avatar
fxy060608 已提交
53 54 55
}

function createSSRServerApp(code: string) {
56
  return code
fxy060608's avatar
fxy060608 已提交
57
}