mainJs.ts 1.2 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import path from 'path'
import slash from 'slash'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '../..'

export function uniMainJsPlugin(options: VitePluginUniResolvedOptions): Plugin {
  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'))
  return {
    name: 'vite:uni-main-js',
    transform(code, id) {
      if (id === mainJsPath || id === mainTsPath) {
fxy060608's avatar
fxy060608 已提交
15 16 17
        let wrapperCode = `function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(plugin)}`
        if (code.includes('createSSRApp')) {
          code = code.replace('createSSRApp', 'createVueSSRApp')
fxy060608's avatar
fxy060608 已提交
18
          wrapperCode = `function createSSRApp(App){return createVueSSRApp(App).use(plugin)}`
fxy060608's avatar
fxy060608 已提交
19 20 21
        } else {
          code = code.replace('createApp', 'createVueApp')
        }
fxy060608's avatar
fxy060608 已提交
22
        return {
fxy060608's avatar
fxy060608 已提交
23
          code: `import { plugin } from '@dcloudio/uni-h5';import '${pagesJsonJsPath}';${wrapperCode};${code}`,
fxy060608's avatar
fxy060608 已提交
24 25 26 27 28 29
          map: this.getCombinedSourcemap(),
        }
      }
    },
  }
}