mainJs.ts 1.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5
import {
  defineUniMainJsPlugin,
  MANIFEST_JSON_JS,
  PAGES_JSON_JS,
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
6
import { APP_CSS_JS } from './appCss'
fxy060608's avatar
fxy060608 已提交
7

fxy060608's avatar
fxy060608 已提交
8 9 10 11 12 13 14
export function uniMainJsPlugin({
  renderer,
  appService,
}: {
  renderer?: 'native'
  appService: boolean
}) {
fxy060608's avatar
fxy060608 已提交
15 16 17 18 19 20
  return defineUniMainJsPlugin((opts) => {
    return {
      name: 'uni:app-nvue-main-js',
      enforce: 'pre',
      transform(code, id) {
        if (opts.filter(id)) {
fxy060608's avatar
fxy060608 已提交
21 22 23 24
          if (renderer !== 'native') {
            return {
              code: `import './${PAGES_JSON_JS}';import('${APP_CSS_JS}').then(()=>{})`,
              map: { mappings: '' },
fxy060608's avatar
fxy060608 已提交
25
            }
fxy060608's avatar
fxy060608 已提交
26 27 28 29 30
          }
          if (appService) {
            code = code.includes('createSSRApp')
              ? createApp(code)
              : createLegacyApp(code)
fxy060608's avatar
fxy060608 已提交
31
            return {
fxy060608's avatar
fxy060608 已提交
32 33 34
              code:
                `import './${MANIFEST_JSON_JS}';\nimport './${PAGES_JSON_JS}';\n` +
                code,
fxy060608's avatar
fxy060608 已提交
35 36 37 38
              map: { mappings: '' },
            }
          }
          return {
fxy060608's avatar
fxy060608 已提交
39
            code: `import './${PAGES_JSON_JS}';`,
fxy060608's avatar
fxy060608 已提交
40 41 42 43 44 45 46 47 48 49 50 51
            map: { mappings: '' },
          }
        }
      },
    }
  })
}

function createApp(code: string) {
  return `${code.replace(
    'createSSRApp',
    'createVueApp as createSSRApp'
fxy060608's avatar
fxy060608 已提交
52
  )};const {app:__app__,Vuex:__Vuex__,Pinia:__Pinia__}=createApp();uni.Vuex=__Vuex__;uni.Pinia=__Pinia__;__app__._component.mpType='app';__app__._component.render=()=>{};__app__.mount({appendChild(){}});`
fxy060608's avatar
fxy060608 已提交
53 54 55
}

function createLegacyApp(code: string) {
fxy060608's avatar
fxy060608 已提交
56
  return `function createApp(rootComponent,rootProps){rootComponent.mpTye='app';rootComponent.render=()=>{};const app=createVueApp(rootComponent,rootProps);const oldMount=app.mount;app.mount=(container)=>{const appVm=oldMount.call(app,container);return appVm;};return app;};${code.replace(
fxy060608's avatar
fxy060608 已提交
57 58 59 60
    'createApp',
    'createVueApp'
  )}`
}