platform.js 15.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
const fs = require('fs')
const path = require('path')

const {
  normalizePath
} = require('./util')

const {
  SCSS,
  SASS
} = require('./scss')

const uniRuntime = '@dcloudio/vue-cli-plugin-uni/packages/mp-vue'
const mpvueRuntime = '@dcloudio/vue-cli-plugin-uni/packages/mpvue'
const megaloRuntime = '@dcloudio/vue-cli-plugin-uni/packages/megalo'

const uniCompiler = '@dcloudio/uni-template-compiler'
const mpvueCompiler = '@dcloudio/vue-cli-plugin-uni/packages/mpvue-template-compiler'
const megaloCompiler = '@megalo/template-compiler'

function getShadowCss () {
  let tagName = 'page'
  if (process.env.UNI_PLATFORM === 'h5') {
    tagName = 'body'
  }
  return `${tagName}::after{position:fixed;content:'';left:-1000px;top:-1000px;-webkit-animation:shadow-preload .1s;-webkit-animation-delay:3s;animation:shadow-preload .1s;animation-delay:3s}@-webkit-keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}@keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}`
}

function getCopyOption (file, options) {
fxy060608's avatar
fxy060608 已提交
30 31 32 33 34 35 36
  if (file === 'wxcomponents') {
    if (!options) {
      options = {}
    }
    // 不拷贝vue,css(这些可能是 uni-migration 转换二来的)
    options.ignore = ['**/*.vue', '**/*.css']
  }
fxy060608's avatar
init v3  
fxy060608 已提交
37 38 39 40 41 42 43 44
  if (path.isAbsolute(file)) {
    if (fs.existsSync(file)) {
      return Object.assign({
        from: file,
        to: path.resolve(process.env.UNI_OUTPUT_DIR)
      }, options)
    }
  }
fxy060608's avatar
fxy060608 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  const from = path.resolve(process.env.UNI_INPUT_DIR, file)
  if (fs.existsSync(from)) {
    return Object.assign({
      from,
      to: path.resolve(process.env.UNI_OUTPUT_DIR, file)
    }, options)
  }
}

function getCopyOptions (files, options = {}, subPackages = true) {
  const copyOptions = []
  files.forEach(file => {
    // 主包
    const copyOption = getCopyOption(file, options)
    if (copyOption) {
      copyOptions.push(copyOption)
    }
    if (subPackages) {
      // 分包
      Object.keys(process.UNI_SUBPACKAGES).forEach(root => { // 分包静态资源
        const subCopyOption = getCopyOption(path.join(root, file), options)
        if (subCopyOption) {
          copyOptions.push(subCopyOption)
        }
      })
    }
  })
  return copyOptions
}

function getStaticCopyOptions (assetsDir) {
  const ignore = []

  Object.keys(PLATFORMS).forEach(platform => {
    if (process.env.UNI_PLATFORM !== platform) {
      ignore.push(platform + '/**/*')
    }
  })

  return getCopyOptions(
    [assetsDir], {
      ignore
    }
  )
}

const PLATFORMS = {
  'h5': {
    global: '',
    exts: false,
    vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
    compiler: false,
97
    megalo: false,
fxy060608's avatar
fxy060608 已提交
98
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
99 100 101 102 103 104 105
    subPackages: false,
    cssVars: {
      '--status-bar-height': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
      const indexCssCopyOptions = [{
        from: require.resolve('@dcloudio/uni-h5/dist/index.css'),
        to: assetsDir,
        transform (content) {
          if (process.env.NODE_ENV === 'production') {
            return content + getShadowCss()
          }
          return content
        }
      }]
      const VUE_APP_INDEX_CSS_HASH = process.env.VUE_APP_INDEX_CSS_HASH
      if (VUE_APP_INDEX_CSS_HASH) {
        const {
          getH5Options
        } = require('./manifest')
        const {
          template
        } = getH5Options()
        const to = path.join(assetsDir, `[name].${VUE_APP_INDEX_CSS_HASH}.[ext]`)
        if (process.env.NODE_ENV === 'production') {
          const templateContent = fs.readFileSync(template, { encoding: 'utf8' })
          if (/\bVUE_APP_INDEX_CSS_HASH\b/.test(templateContent)) {
            indexCssCopyOptions[0].to = to
          }
        } else {
          const indexCssCopyOption = Object.assign({}, indexCssCopyOptions[0])
          indexCssCopyOption.to = to
          indexCssCopyOptions.push(indexCssCopyOption)
        }
      }
fxy060608's avatar
fxy060608 已提交
136 137
      return [
        ...getStaticCopyOptions(assetsDir),
138
        ...indexCssCopyOptions,
fxy060608's avatar
fxy060608 已提交
139 140 141 142 143 144 145 146
        ...getCopyOptions(['hybrid/html'])
      ]
    }
  },
  'app-plus': {
    global: 'wx',
    exts: {
      style: '.wxss',
147 148
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
149 150 151 152
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
153
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
154 155
    subPackages: false,
    cssVars: {
Q
qiang 已提交
156
      '--window-top': '0px'
fxy060608's avatar
fxy060608 已提交
157 158
    },
    copyWebpackOptions ({
fxy060608's avatar
fxy060608 已提交
159 160
      assetsDir,
      vueOptions
Q
qiang 已提交
161 162 163
    }) {
      if (
        vueOptions &&
fxy060608's avatar
fxy060608 已提交
164
        vueOptions.pluginOptions &&
fxy060608's avatar
fxy060608 已提交
165 166 167 168 169 170
        vueOptions.pluginOptions['uni-app-plus'] &&
        vueOptions.pluginOptions['uni-app-plus']['view']
      ) { // app-view 无需拷贝资源(app-service 已经做了)
        return []
      }

fxy060608's avatar
fxy060608 已提交
171
      const files = ['hybrid/html']
172
      let wxcomponents = []
fxy060608's avatar
init v3  
fxy060608 已提交
173
      if (!process.env.UNI_USING_NATIVE && !process.env.UNI_USING_V3) {
174 175 176
        wxcomponents = getCopyOptions(['wxcomponents'], {
          to: path.resolve(process.env.UNI_OUTPUT_TMP_DIR, 'wxcomponents')
        })
fxy060608's avatar
fxy060608 已提交
177
      }
fxy060608's avatar
init v3  
fxy060608 已提交
178
      let template = []
fxy060608's avatar
fxy060608 已提交
179
      let view = []
fxy060608's avatar
init v3  
fxy060608 已提交
180
      if (process.env.UNI_USING_V3) {
fxy060608's avatar
fxy060608 已提交
181 182
        view = getCopyOptions([
          require.resolve('@dcloudio/uni-app-plus/dist/view.css'),
fxy060608's avatar
fxy060608 已提交
183
          require.resolve('@dcloudio/uni-app-plus/dist/view.umd.min.js')
fxy060608's avatar
fxy060608 已提交
184
        ])
Q
qiang 已提交
185 186 187
        template = [
          ...getCopyOptions([path.resolve(__dirname, '../template/common')]),
          ...getCopyOptions([path.resolve(__dirname, '../template/v3')])
fxy060608's avatar
fxy060608 已提交
188
        ]
fxy060608's avatar
init v3  
fxy060608 已提交
189
      }
fxy060608's avatar
fxy060608 已提交
190
      return [
fxy060608's avatar
fxy060608 已提交
191
        ...view,
fxy060608's avatar
init v3  
fxy060608 已提交
192
        ...template,
fxy060608's avatar
fxy060608 已提交
193
        ...getStaticCopyOptions(assetsDir),
194
        ...wxcomponents,
fxy060608's avatar
fxy060608 已提交
195 196 197 198 199 200 201 202
        ...getCopyOptions(files)
      ]
    }
  },
  'mp-qq': {
    global: 'wx',
    exts: {
      style: '.qss',
203 204
      template: '.qml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
205 206 207 208
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
209
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    subPackages: true,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    project: 'project.config.json',
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['wxcomponents'])
      ]
    }
  },
  'mp-weixin': {
    global: 'wx',
    exts: {
      style: '.wxss',
230 231
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
232 233 234 235
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
236
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    subPackages: true,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    project: 'project.config.json',
    copyWebpackOptions ({
      assetsDir,
      manifestPlatformOptions
    }) {
      const files = [
        'sitemap.json',
        'ext.json',
        'custom-tab-bar'
      ]
      if (manifestPlatformOptions.workers) {
        files.push(manifestPlatformOptions.workers)
      }
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['wxcomponents']),
        ...getCopyOptions(files, {}, false)
      ]
    }
  },
  'mp-baidu': {
    global: 'swan',
    exts: {
      style: '.css',
267 268
      template: '.swan',
      filter: '.filter.js'
fxy060608's avatar
fxy060608 已提交
269 270 271 272
    },
    vue: megaloRuntime,
    compiler: megaloCompiler,
    megalo: 'swan',
273
    filterTag: 'filter',
fxy060608's avatar
fxy060608 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    subPackages: true,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    project: 'project.swan.json',
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['swancomponents'])
      ]
    }
  },
  'mp-alipay': {
    global: 'my',
    exts: {
      style: '.acss',
294 295
      template: '.axml',
      filter: '.sjs'
fxy060608's avatar
fxy060608 已提交
296 297 298 299
    },
    vue: megaloRuntime,
    compiler: megaloCompiler,
    megalo: 'alipay',
fxy060608's avatar
fxy060608 已提交
300
    filterTag: 'sjs',
fxy060608's avatar
fxy060608 已提交
301
    subPackages: true,
fxy060608's avatar
fxy060608 已提交
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 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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['mycomponents'])
      ]
    }
  },
  'mp-toutiao': {
    global: 'tt',
    exts: {
      style: '.ttss',
      template: '.ttml'
    },
    vue: megaloRuntime,
    compiler: megaloCompiler,
    megalo: 'tt',
    subPackages: false,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    project: 'project.tt.json',
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['ttcomponents'])
      ]
    }
  }
}
// 解决 vue-cli-service lint 时 UNI_PLATFORM 不存在
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'

const platform = PLATFORMS[process.env.UNI_PLATFORM]

const preprocessContext = {}

Object.keys(PLATFORMS).forEach(platform => {
  preprocessContext[platform.toUpperCase()] = false
})

preprocessContext[process.env.UNI_PLATFORM.toUpperCase()] = true

preprocessContext['MP'] = false
preprocessContext['APP'] = false
preprocessContext['APP-PLUS-NVUE'] = false
preprocessContext['APP_PLUS_NVUE'] = false

preprocessContext['APP-VUE'] = false
preprocessContext['APP_VUE'] = false
preprocessContext['APP-NVUE'] = false
preprocessContext['APP_NVUE'] = false

if (process.env.UNI_PLATFORM === 'app-plus') {
  preprocessContext['APP-VUE'] = true
  preprocessContext['APP_VUE'] = true
}

if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
  preprocessContext['MP'] = true
}

if (process.env.UNI_PLATFORM.indexOf('app-') === 0) {
  preprocessContext['APP'] = true
}

if (process.UNI_SCRIPT_DEFINE && Object.keys(process.UNI_SCRIPT_DEFINE).length) {
  Object.keys(process.UNI_SCRIPT_DEFINE).forEach(name => {
    preprocessContext[name] = process.UNI_SCRIPT_DEFINE[name]
  })
}

Object.keys(preprocessContext).forEach(platform => {
  if (platform.indexOf('-') !== -1) {
    preprocessContext[platform.replace(/-/g, '_')] = preprocessContext[platform]
  }
})

const nvuePreprocessContext = Object.assign({}, preprocessContext, {
  'APP-VUE': false,
  'APP_VUE': false,
  'APP-NVUE': true,
  'APP_NVUE': true,
  'APP-PLUS-NVUE': true,
  'APP_PLUS_NVUE': true
})

const isInHBuilderX = fs.existsSync(path.resolve(process.env.UNI_CLI_CONTEXT, 'bin/uniapp-cli.js'))

let isInHBuilderXAlpha = false

if (isInHBuilderX) {
  try {
    if (require(path.resolve(process.env.UNI_CLI_CONTEXT, '../about/package.json')).alpha) {
      isInHBuilderXAlpha = true
    }
  } catch (e) {

  }
}

let sourceRoot = false

function devtoolModuleFilenameTemplate (info) {
  if (!sourceRoot) {
    if (isInHBuilderX) {
      sourceRoot = normalizePath(process.env.UNI_INPUT_DIR)
    } else {
      sourceRoot = normalizePath(process.env.UNI_CLI_CONTEXT)
    }
  }
  let filePath = false
  const absoluteResourcePath = normalizePath(info.absoluteResourcePath)
  if (
    absoluteResourcePath.indexOf(sourceRoot) !== -1 &&
    (
      absoluteResourcePath.endsWith('.js') ||
      absoluteResourcePath.endsWith('.ts')
    )
  ) {
    filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
    if (
      filePath.indexOf('node_modules/@dcloudio') === 0 ||
      filePath.indexOf('node_modules/vue-loader') === 0 ||
      filePath.indexOf('node_modules/webpack') === 0
    ) {
      filePath = false
    }
  } else if (
    !info.moduleId &&
    (
      absoluteResourcePath.endsWith('.vue') ||
      absoluteResourcePath.endsWith('.nvue')
    )
  ) {
    if (
      absoluteResourcePath.indexOf('src') !== 0 &&
      absoluteResourcePath.indexOf('node-modules') !== 0
    ) {
      filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
    } else {
      filePath = absoluteResourcePath
    }
  }
  if (
    filePath &&
    filePath !== 'main.js' &&
    filePath !== 'main.ts' &&
    filePath !== 'src/main.js' &&
    filePath !== 'src/main.ts'
  ) {
    return `uni-app:///${filePath}`
  }
465 466 467 468
}

const NODE_MODULES_REGEX = /(\.\.\/)?node_modules/g

fxy060608's avatar
fxy060608 已提交
469 470 471 472 473 474
function normalizeNodeModules (str) {
  str = str.replace(NODE_MODULES_REGEX, 'node-modules')
  if (process.env.UNI_PLATFORM === 'mp-alipay') {
    str = str.replace('node-modules/@', 'node-modules/npm-scope-')
  }
  return str
475
}
fxy060608's avatar
fxy060608 已提交
476

477
module.exports = {
fxy060608's avatar
fxy060608 已提交
478
  normalizeNodeModules,
fxy060608's avatar
fxy060608 已提交
479 480
  isInHBuilderX,
  isInHBuilderXAlpha,
fxy060608's avatar
fxy060608 已提交
481
  runByHBuilderX: isInHBuilderX || fs.existsSync(path.resolve(process.env.UNI_HBUILDERX_PLUGINS || '', 'weapp-tools')),
fxy060608's avatar
fxy060608 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  devtoolModuleFilenameTemplate,
  getFlexDirection (json) {
    let flexDir = 'column'
    if (json && json['nvue'] && json['nvue']['flex-direction']) {
      flexDir = json['nvue']['flex-direction']
      const flexDirs = ['row', 'row-reverse', 'column', 'column-reverse']
      if (flexDirs.indexOf(flexDir) === -1) {
        flexDir = 'column'
      }
    }
    return flexDir
  },
  jsPreprocessOptions: {
    type: 'js',
    context: preprocessContext
  },
  cssPreprocessOptions: {
    type: 'css',
    context: preprocessContext
  },
  htmlPreprocessOptions: {
    type: 'html',
    context: preprocessContext
  },
  nvueCssPreprocessOptions: {
    type: 'css',
    context: nvuePreprocessContext
  },
  nvueJsPreprocessOptions: {
    type: 'js',
    context: nvuePreprocessContext
  },
  nvueHtmlPreprocessOptions: {
    type: 'html',
    context: nvuePreprocessContext
  },
  isSupportSubPackages () {
    return platform.subPackages
  },
  getPlatforms () {
    return Object.keys(PLATFORMS)
  },
  getPlatformCopy () {
    return platform.copyWebpackOptions
  },
  getPlatformGlobal () {
    return platform.global
  },
  getPlatformExts () {
    return platform.exts
  },
  getPlatformTarget () {
    return platform.megalo
  },
  getPlatformProject () {
    return platform.project
  },
539 540 541
  getPlatformFilterTag () {
    return platform.filterTag
  },
fxy060608's avatar
fxy060608 已提交
542 543 544 545
  getPlatformVue (vueOptions) {
    if (process.env.UNI_PLATFORM === 'h5' && vueOptions && vueOptions.runtimeCompiler) {
      return '@dcloudio/vue-cli-plugin-uni/packages/h5-vue/dist/vue.esm.js'
    }
fxy060608's avatar
init v3  
fxy060608 已提交
546 547 548
    if (process.env.UNI_PLATFORM === 'app-plus' && process.env.UNI_USING_V3) {
      return '@dcloudio/uni-app-plus/dist/service.runtime.esm.js'
    }
fxy060608's avatar
fxy060608 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    if (process.env.UNI_USING_COMPONENTS) {
      return uniRuntime
    }
    return platform.vue
  },
  getPlatformCompiler () {
    if (process.env.UNI_USING_COMPONENTS || process.env.UNI_PLATFORM === 'h5') {
      return require(uniCompiler)
    }
    return require(platform.compiler)
  },
  getPlatformCssVars () {
    return platform.cssVars
  },
  getPlatformCssnano () {
    return {
      calc: false,
      orderedValues: false,
      mergeLonghand: false,
      mergeRules: false,
      cssDeclarationSorter: false,
      discardComments: false,
      discardDuplicates: false // 条件编译会导致重复
    }
  },
  getShadowCss,
  getShadowTemplate (colorType = 'grey') {
    let tagName = 'cover-image'
    if (process.env.UNI_PLATFORM === 'mp-toutiao') {
      tagName = 'image'
    }
    return `<${tagName} src="https://cdn.dcloud.net.cn/img/shadow-${colorType}.png" style="z-index:998;position:fixed;left:0;top:0;width:100%;height:3px;"/>`
  },
  getPlatformScss () {
    return SCSS
  },
  getPlatformSass () {
    return SASS
  }
588
}