h5.js 13.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
const fs = require('fs')
const path = require('path')

const {
fxy060608's avatar
fxy060608 已提交
5
  hasOwn,
fxy060608's avatar
fxy060608 已提交
6 7 8
  getPlatforms,
  getH5Options,
  getFlexDirection,
fxy060608's avatar
fxy060608 已提交
9 10
  getNetworkTimeout,
  normalizePath
fxy060608's avatar
fxy060608 已提交
11 12
} = require('@dcloudio/uni-cli-shared')

fxy060608's avatar
fxy060608 已提交
13 14
const {
  addPageUsingComponents
fxy060608's avatar
fxy060608 已提交
15 16
} = require('@dcloudio/uni-cli-shared/lib/pages')

d-u-a's avatar
d-u-a 已提交
17
const compilerVersion = require('@dcloudio/webpack-uni-pages-loader/package.json')['uni-app'].compilerVersion
fxy060608's avatar
fxy060608 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

const PLATFORMS = getPlatforms()

const removePlatformStyle = function (style) {
  Object.keys(style).forEach(name => {
    if (PLATFORMS.includes(name)) {
      delete style[name]
    }
  })
}

const getPageComponents = function (inputDir, pagesJson) {
  const firstPagePath = pagesJson.pages[0].path
  const pages = pagesJson.pages

  // 解析分包
  if (pagesJson.subPackages && pagesJson.subPackages.length) {
    pagesJson.subPackages.forEach(({
      root,
      pages: subPages
    }) => {
      if (root && subPages.length) {
        subPages.forEach(subPage => {
          subPage.path = normalizePath(path.join(root, subPage.path))
          pages.push(subPage)
        })
      }
    })
  }

  const tabBarList = (pagesJson.tabBar && pagesJson.tabBar.list) || []
  tabBarList.forEach(item => { // 添加全部属性,方便 Vue 响应式
    item.text = item.text || ''
    item.iconPath = item.iconPath || ''
    item.selectedIconPath = item.selectedIconPath || ''
    item.redDot = false
    item.badge = ''
  })

  if (tabBarList.length) { // 添加全部属性,方便 Vue 响应式
    pagesJson.tabBar.color = pagesJson.tabBar.color || '#999'
    pagesJson.tabBar.selectedColor = pagesJson.tabBar.selectedColor || '#007aff'
60
    pagesJson.tabBar.backgroundColor = pagesJson.tabBar.backgroundColor || ''
fxy060608's avatar
fxy060608 已提交
61 62 63
    pagesJson.tabBar.borderStyle = pagesJson.tabBar.borderStyle || 'black'
  }

fxy060608's avatar
fxy060608 已提交
64 65 66 67 68
  const globalStyle = Object.assign({}, pagesJson.globalStyle || {})

  Object.assign(
    globalStyle,
    globalStyle['app-plus'] || {},
fxy060608's avatar
fxy060608 已提交
69
    globalStyle.h5 || {}
fxy060608's avatar
fxy060608 已提交
70 71
  )

fxy060608's avatar
fxy060608 已提交
72 73 74 75
  if (process.env.UNI_SUB_PLATFORM) {
    Object.assign(globalStyle, globalStyle[process.env.UNI_SUB_PLATFORM] || {})
  }

fxy060608's avatar
fxy060608 已提交
76 77
  process.UNI_H5_PAGES_JSON = {
    pages: {},
fxy060608's avatar
fxy060608 已提交
78
    globalStyle
fxy060608's avatar
fxy060608 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  }

  removePlatformStyle(process.UNI_H5_PAGES_JSON.globalStyle)

  return pages.map(page => {
    const name = page.path.replace(/\//g, '-')
    const pagePath = normalizePath(path.resolve(inputDir, page.path))
    const props = page.style || {}
    const isEntry = firstPagePath === page.path
    const tabBarIndex = tabBarList.findIndex(tabBarPage => tabBarPage.pagePath === page.path)
    const isTabBar = tabBarIndex !== -1

    let isNVue = false
    if (process.env.UNI_USING_NVUE_COMPILER) {
      if (!fs.existsSync(pagePath + '.vue') && fs.existsSync(pagePath + '.nvue')) {
        isNVue = true
      }
    }
    // 解析 titleNView,pullToRefresh
fxy060608's avatar
fxy060608 已提交
98
    const h5Options = Object.assign({}, props['app-plus'] || {}, props.h5 || {})
fxy060608's avatar
fxy060608 已提交
99

fxy060608's avatar
fxy060608 已提交
100 101 102 103 104
    if (process.env.UNI_SUB_PLATFORM) {
      Object.assign(h5Options, props[process.env.UNI_SUB_PLATFORM] || {})
      Object.assign(props, props[process.env.UNI_SUB_PLATFORM] || {})
    }

fxy060608's avatar
fxy060608 已提交
105 106
    removePlatformStyle(h5Options)

fxy060608's avatar
fxy060608 已提交
107
    if (hasOwn(h5Options, 'titleNView')) {
fxy060608's avatar
fxy060608 已提交
108 109
      props.titleNView = h5Options.titleNView
    }
fxy060608's avatar
fxy060608 已提交
110
    if (hasOwn(h5Options, 'pullToRefresh')) {
fxy060608's avatar
fxy060608 已提交
111 112 113 114
      props.pullToRefresh = h5Options.pullToRefresh
    }

    let windowTop = 44
Q
qiang 已提交
115 116
    const pageStyle = Object.assign({}, globalStyle, props)
    const titleNViewTypeList = {
fxy060608's avatar
fxy060608 已提交
117 118 119
      none: 'default',
      auto: 'transparent',
      always: 'float'
Q
qiang 已提交
120 121 122 123 124 125 126 127 128 129 130
    }
    let titleNView = pageStyle.titleNView
    titleNView = Object.assign({}, {
      type: pageStyle.navigationStyle === 'custom' ? 'none' : 'default'
    }, pageStyle.transparentTitle in titleNViewTypeList ? {
      type: titleNViewTypeList[pageStyle.transparentTitle],
      backgroundColor: 'rgba(0,0,0,0)'
    } : null, typeof titleNView === 'object' ? titleNView : (typeof titleNView === 'boolean' ? {
      type: titleNView ? 'default' : 'none'
    } : null))
    if (titleNView.type === 'none' || titleNView.type === 'transparent') {
Q
qiang 已提交
131
      windowTop = 0
fxy060608's avatar
fxy060608 已提交
132 133 134 135
    }

    // 删除 app-plus 平台配置
    delete props['app-plus']
fxy060608's avatar
fxy060608 已提交
136
    delete props.h5
fxy060608's avatar
fxy060608 已提交
137 138 139 140

    if (process.env.UNI_SUB_PLATFORM) {
      delete props[process.env.UNI_SUB_PLATFORM]
    }
fxy060608's avatar
fxy060608 已提交
141 142 143

    process.UNI_H5_PAGES_JSON.pages[page.path] = props

fxy060608's avatar
fxy060608 已提交
144 145 146
    // 缓存usingComponents
    addPageUsingComponents(page.path, props.usingComponents)

fxy060608's avatar
fxy060608 已提交
147 148 149 150 151 152 153 154 155 156
    return {
      name,
      route: page.path,
      path: pagePath,
      props,
      isNVue,
      isEntry,
      isTabBar,
      tabBarIndex,
      isQuit: isEntry || isTabBar,
fxy060608's avatar
fxy060608 已提交
157 158 159 160 161
      windowTop,
      topWindow: pageStyle.topWindow,
      leftWindow: pageStyle.leftWindow,
      rightWindow: pageStyle.rightWindow,
      maxWidth: pageStyle.maxWidth
fxy060608's avatar
fxy060608 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    }
  }).filter(pageComponents => !!pageComponents)
}

const genRegisterPageVueComponentsCode = function (pageComponents) {
  return pageComponents
    .map(({
      name,
      path,
      isNVue,
      isQuit,
      isEntry,
      isTabBar
    }) => {
      const ext = isNVue ? '.nvue' : '.vue'

      return `Vue.component('${name}', resolve=>{
const component = {
  component:require.ensure([], () => resolve(require('${path}${ext}')), '${name}'),
  delay:__uniConfig['async'].delay,
  timeout: __uniConfig['async'].timeout
}
if(__uniConfig['async']['loading']){
  component.loading={
    name:'SystemAsyncLoading',
    render(createElement){
      return createElement(__uniConfig['async']['loading'])
    }
  }
}
if(__uniConfig['async']['error']){
  component.error={
    name:'SystemAsyncError',
    render(createElement){
      return createElement(__uniConfig['async']['error'])
    }
  }
}
return component
})`
    })
    .join('\n')
}

const genPageRoutes = function (pageComponents) {
  let id = 1
  return pageComponents
    .map(({
      name,
      route,
      props,
      isNVue,
      isQuit,
      isEntry,
      isTabBar,
      windowTop,
fxy060608's avatar
fxy060608 已提交
218 219 220 221 222
      tabBarIndex,
      topWindow,
      leftWindow,
      rightWindow,
      maxWidth
fxy060608's avatar
fxy060608 已提交
223 224 225 226 227 228 229 230 231 232
    }) => {
      return `
{
path: '/${isEntry ? '' : route}',${isEntry ? '\nalias:\'/' + route + '\',' : ''}
component: {
  render (createElement) {
    return createElement(
      'Page',
      {
        props: Object.assign({
fxy060608's avatar
fxy060608 已提交
233
          ${isQuit ? 'isQuit:true,\n' : ''}${isEntry ? 'isEntry:true,\n' : ''}${isTabBar ? 'isTabBar:true,\n' : ''}
fxy060608's avatar
fxy060608 已提交
234
          ${topWindow === false ? 'topWindow:false,\n' : ''}${leftWindow === false ? 'leftWindow:false,\n' : ''}${rightWindow === false ? 'rightWindow:false,\n' : ''}
fxy060608's avatar
fxy060608 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247
          ${isTabBar ? ('tabBarIndex:' + tabBarIndex) : ''}
        },__uniConfig.globalStyle,${JSON.stringify(props)})
      },
      [
        createElement('${name}', {
          slot: 'page'
        })
      ]
    )
  }
},
meta:{${isQuit ? '\nid:' + (id++) + ',' : ''}
  name:'${name}',
fxy060608's avatar
fxy060608 已提交
248
  isNVue:${isNVue},maxWidth:${maxWidth || 0},${topWindow === false ? 'topWindow:false,\n' : ''}${leftWindow === false ? 'leftWindow:false,\n' : ''}${rightWindow === false ? 'rightWindow:false,\n' : ''}
fxy060608's avatar
fxy060608 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  pagePath:'${route}'${isQuit ? ',\nisQuit:true' : ''}${isEntry ? ',\nisEntry:true' : ''}${isTabBar ? ',\nisTabBar:true' : ''}${tabBarIndex !== -1 ? (',\ntabBarIndex:' + tabBarIndex) : ''},
  windowTop:${windowTop}
}
}`
    })
}

const genSystemRoutes = function () {
  return [
    `
{
path: '/preview-image',
component: {
  render (createElement) {
    return createElement(
      'Page',
      {
        props:{
          navigationStyle:'custom'
        }
      },
      [
        createElement('system-preview-image', {
          slot: 'page'
        })
      ]
    )
  }
},
meta:{
  name:'preview-image',
  pagePath:'/preview-image'
}
}
    `,
    `
{
path: '/choose-location',
component: {
  render (createElement) {
    return createElement(
      'Page',
      {
        props:{
          navigationStyle:'custom'
        }
      },
      [
        createElement('system-choose-location', {
          slot: 'page'
        })
      ]
    )
  }
},
meta:{
  name:'choose-location',
  pagePath:'/choose-location'
}
}
    `,
    `
{
path: '/open-location',
component: {
  render (createElement) {
    return createElement(
      'Page',
      {
        props:{
          navigationStyle:'custom'
        }
      },
      [
        createElement('system-open-location', {
          slot: 'page'
        })
      ]
    )
  }
},
meta:{
  name:'open-location',
  pagePath:'/open-location'
}
}
    `
  ]
}

fxy060608's avatar
fxy060608 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
function filterPages (pagesJson, includes) {
  const pages = []
  let subPackages = pagesJson.subPackages || []
  if (!Array.isArray(subPackages)) {
    subPackages = []
  }
  includes.forEach(includePagePath => {
    let page = pagesJson.pages.find(page => page.path === includePagePath)
    if (!page) {
      for (let i = 0; i < subPackages.length; i++) {
        const {
          root,
          pages: subPages
        } = subPackages[i]
        page = subPages.find(subPage => normalizePath(path.join(root, subPage.path)) === includePagePath)
        if (page) {
          break
        }
      }
    }
    if (!page) {
      console.error(`${includePagePath} is not found`)
    }
    pages.push(page)
  })
  pagesJson.pages = pages
}

fxy060608's avatar
fxy060608 已提交
367 368 369
function genLayoutComponentsCode (pagesJson) {
  const code = []
  const {
fxy060608's avatar
fxy060608 已提交
370
    topWindow,
fxy060608's avatar
fxy060608 已提交
371 372 373
    leftWindow,
    rightWindow
  } = pagesJson
fxy060608's avatar
fxy060608 已提交
374 375 376 377 378 379 380
  if (topWindow && topWindow.path) {
    code.push(
      `import TopWindow from './${topWindow.path}';
${topWindow.style ? ('TopWindow.style=' + JSON.stringify(topWindow.style)) : ''}
Vue.component('VUniTopWindow',TopWindow);`
    )
  }
fxy060608's avatar
fxy060608 已提交
381 382
  if (leftWindow && leftWindow.path) {
    code.push(
fxy060608's avatar
fxy060608 已提交
383
      `import LeftWindow from './${leftWindow.path}';
fxy060608's avatar
fxy060608 已提交
384 385 386 387 388 389 390 391
${leftWindow.style ? ('LeftWindow.style=' + JSON.stringify(leftWindow.style)) : ''}
Vue.component('VUniLeftWindow',LeftWindow);`
    )
  }

  if (rightWindow && rightWindow.path) {
    code.push(
      `
fxy060608's avatar
fxy060608 已提交
392
import RightWindow from './${rightWindow.path}';
fxy060608's avatar
fxy060608 已提交
393 394 395 396 397 398 399
${rightWindow.style ? ('RightWindow.style=' + JSON.stringify(rightWindow.style)) : ''}
Vue.component('VUniRightWindow',RightWindow);`
    )
  }
  return code.join('\n')
}

fxy060608's avatar
fxy060608 已提交
400
module.exports = function (pagesJson, manifestJson, loader) {
fxy060608's avatar
fxy060608 已提交
401 402
  const inputDir = process.env.UNI_INPUT_DIR

fxy060608's avatar
fxy060608 已提交
403 404 405 406
  global.uniPlugin.configurePages.forEach(configurePages => {
    configurePages(pagesJson, manifestJson, loader)
  })

fxy060608's avatar
fxy060608 已提交
407 408 409 410 411 412 413 414 415 416 417
  if (loader.resourceQuery) {
    const loaderUtils = require('loader-utils')
    const params = loaderUtils.parseQuery(loader.resourceQuery)
    if (params.pages) {
      try {
        const pages = JSON.parse(params.pages)
        if (Array.isArray(pages)) {
          filterPages(pagesJson, pages)
        }
      } catch (e) {}
    }
fxy060608's avatar
fxy060608 已提交
418 419
  }

fxy060608's avatar
fxy060608 已提交
420
  const pageComponents = getPageComponents(inputDir, pagesJson)
Q
qiang 已提交
421

422
  pagesJson.globalStyle = process.UNI_H5_PAGES_JSON.globalStyle
fxy060608's avatar
fxy060608 已提交
423 424 425 426 427 428 429 430
  delete pagesJson.pages
  delete pagesJson.subPackages

  const h5 = getH5Options(manifestJson)

  const networkTimeoutConfig = getNetworkTimeout(manifestJson)

  const sdkConfigs = h5.sdkConfigs || {}
Q
qiang 已提交
431 432 433

  const qqMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key
  const googleMapKey = sdkConfigs.maps && sdkConfigs.maps.google && sdkConfigs.maps.google.key
fxy060608's avatar
fxy060608 已提交
434

Q
qiang 已提交
435 436
  let locale = manifestJson.locale
  locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : ''
Q
qiang 已提交
437

fxy060608's avatar
fxy060608 已提交
438 439
  return `
import Vue from 'vue'
fxy060608's avatar
fxy060608 已提交
440
${genLayoutComponentsCode(pagesJson)}
fxy060608's avatar
fxy060608 已提交
441
const locales = ${fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'locale')) ? 'require.context(\'./locale\', false, /.json$/)' : '{keys(){return []}}'}
fxy060608's avatar
fxy060608 已提交
442 443
global['____${h5.appid}____'] = true;
delete global['____${h5.appid}____'];
fxy060608's avatar
fxy060608 已提交
444
global.__uniConfig = ${JSON.stringify(pagesJson)};
d-u-a's avatar
d-u-a 已提交
445
global.__uniConfig.compilerVersion = '${compilerVersion}';
fxy060608's avatar
fxy060608 已提交
446
global.__uniConfig.router = ${JSON.stringify(h5.router)};
fxy060608's avatar
fxy060608 已提交
447
global.__uniConfig.publicPath = ${JSON.stringify(h5.publicPath)};
fxy060608's avatar
fxy060608 已提交
448
global.__uniConfig['async'] = ${JSON.stringify(h5.async)};
fxy060608's avatar
fxy060608 已提交
449 450 451 452
global.__uniConfig.debug = ${manifestJson.debug === true};
global.__uniConfig.networkTimeout = ${JSON.stringify(networkTimeoutConfig)};
global.__uniConfig.sdkConfigs = ${JSON.stringify(sdkConfigs)};
global.__uniConfig.qqMapKey = ${JSON.stringify(qqMapKey)};
Q
qiang 已提交
453
global.__uniConfig.googleMapKey = ${JSON.stringify(googleMapKey)};
Q
qiang 已提交
454
global.__uniConfig.locale = ${JSON.stringify(locale)};
fxy060608's avatar
fxy060608 已提交
455
global.__uniConfig.fallbackLocale = ${JSON.stringify(manifestJson.fallbackLocale)};
fxy060608's avatar
fxy060608 已提交
456
global.__uniConfig.locales = locales.keys().reduce((res,key)=>{const locale=key.replace(/\\.\\/(uni-app.)?(.*).json/,'$2');const messages = locales(key);Object.assign(res[locale]||(res[locale]={}),messages.common||messages);return res},{});
fxy060608's avatar
fxy060608 已提交
457
global.__uniConfig.nvue = ${JSON.stringify({ 'flex-direction': getFlexDirection(manifestJson['app-plus']) })}
fxy060608's avatar
fxy060608 已提交
458
global.__uniConfig.__webpack_chunk_load__ = __webpack_chunk_load__
fxy060608's avatar
fxy060608 已提交
459
${genRegisterPageVueComponentsCode(pageComponents)}
fxy060608's avatar
fxy060608 已提交
460
global.__uniRoutes=[${genPageRoutes(pageComponents).concat(genSystemRoutes()).join(',')}]
461
global.UniApp && new global.UniApp();
fxy060608's avatar
fxy060608 已提交
462
`
fxy060608's avatar
fxy060608 已提交
463
}