platform.js 15.8 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
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'

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 已提交
24 25 26 27 28 29 30
  if (file === 'wxcomponents') {
    if (!options) {
      options = {}
    }
    // 不拷贝vue,css(这些可能是 uni-migration 转换二来的)
    options.ignore = ['**/*.vue', '**/*.css']
  }
fxy060608's avatar
init v3  
fxy060608 已提交
31 32 33 34 35 36 37 38
  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 已提交
39 40 41 42 43 44 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
  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,
fxy060608's avatar
fxy060608 已提交
91
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
92 93 94 95 96 97 98
    subPackages: false,
    cssVars: {
      '--status-bar-height': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      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') {
fxy060608's avatar
fxy060608 已提交
119 120 121
          const templateContent = fs.readFileSync(template, {
            encoding: 'utf8'
          })
122 123 124 125 126 127 128 129 130
          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 已提交
131 132
      return [
        ...getStaticCopyOptions(assetsDir),
133
        ...indexCssCopyOptions,
fxy060608's avatar
fxy060608 已提交
134 135 136 137 138 139 140 141
        ...getCopyOptions(['hybrid/html'])
      ]
    }
  },
  'app-plus': {
    global: 'wx',
    exts: {
      style: '.wxss',
142 143
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
144
    },
145
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
146
    subPackages: false,
Q
qiang 已提交
147
    cssVars: {},
fxy060608's avatar
fxy060608 已提交
148
    copyWebpackOptions ({
fxy060608's avatar
fxy060608 已提交
149 150
      assetsDir,
      vueOptions
Q
qiang 已提交
151 152 153
    }) {
      if (
        vueOptions &&
fxy060608's avatar
fxy060608 已提交
154
        vueOptions.pluginOptions &&
fxy060608's avatar
fxy060608 已提交
155 156 157 158 159 160
        vueOptions.pluginOptions['uni-app-plus'] &&
        vueOptions.pluginOptions['uni-app-plus']['view']
      ) { // app-view 无需拷贝资源(app-service 已经做了)
        return []
      }

fxy060608's avatar
fxy060608 已提交
161
      const files = ['hybrid/html']
162
      let wxcomponents = []
fxy060608's avatar
init v3  
fxy060608 已提交
163
      if (!process.env.UNI_USING_NATIVE && !process.env.UNI_USING_V3) {
164 165 166
        wxcomponents = getCopyOptions(['wxcomponents'], {
          to: path.resolve(process.env.UNI_OUTPUT_TMP_DIR, 'wxcomponents')
        })
fxy060608's avatar
fxy060608 已提交
167
      }
fxy060608's avatar
init v3  
fxy060608 已提交
168
      let template = []
fxy060608's avatar
fxy060608 已提交
169
      let view = []
fxy060608's avatar
init v3  
fxy060608 已提交
170
      if (process.env.UNI_USING_V3) {
fxy060608's avatar
fxy060608 已提交
171 172
        view = getCopyOptions([
          require.resolve('@dcloudio/uni-app-plus/dist/view.css'),
fxy060608's avatar
fxy060608 已提交
173
          require.resolve('@dcloudio/uni-app-plus/dist/view.umd.min.js')
fxy060608's avatar
fxy060608 已提交
174
        ])
Q
qiang 已提交
175 176 177
        template = [
          ...getCopyOptions([path.resolve(__dirname, '../template/common')]),
          ...getCopyOptions([path.resolve(__dirname, '../template/v3')])
fxy060608's avatar
fxy060608 已提交
178
        ]
fxy060608's avatar
init v3  
fxy060608 已提交
179
      }
fxy060608's avatar
fxy060608 已提交
180
      return [
fxy060608's avatar
fxy060608 已提交
181
        ...view,
fxy060608's avatar
init v3  
fxy060608 已提交
182
        ...template,
fxy060608's avatar
fxy060608 已提交
183
        ...getStaticCopyOptions(assetsDir),
184
        ...wxcomponents,
fxy060608's avatar
fxy060608 已提交
185 186 187 188 189 190 191 192
        ...getCopyOptions(files)
      ]
    }
  },
  'mp-qq': {
    global: 'wx',
    exts: {
      style: '.qss',
193 194
      template: '.qml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
195
    },
196
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    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',
217 218
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
219
    },
220
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    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',
251 252
      template: '.swan',
      filter: '.filter.js'
fxy060608's avatar
fxy060608 已提交
253
    },
254
    filterTag: 'filter',
fxy060608's avatar
fxy060608 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    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',
275 276
      template: '.axml',
      filter: '.sjs'
fxy060608's avatar
fxy060608 已提交
277
    },
fxy060608's avatar
fxy060608 已提交
278
    filterTag: 'sjs',
fxy060608's avatar
fxy060608 已提交
279
    subPackages: true,
fxy060608's avatar
fxy060608 已提交
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
    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'
    },
    subPackages: false,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    project: 'project.tt.json',
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['ttcomponents'])
      ]
    }
fxy060608's avatar
fxy060608 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  },
  'quickapp': {
    vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
    subPackages: false,
    cssVars: {
      '--status-bar-height': '25px',
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        ...getCopyOptions(['qacomponents'])
      ]
    }
fxy060608's avatar
fxy060608 已提交
332 333 334
  }
}
// 解决 vue-cli-service lint 时 UNI_PLATFORM 不存在
fxy060608's avatar
fxy060608 已提交
335 336 337 338
if (process.env.UNI_PLATFORM === 'mp-360') {
  process.env.UNI_PLATFORM = 'h5'
  process.env.UNI_SUB_PLATFORM = 'mp-360'
}
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 367 368 369 370 371 372 373
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
}

fxy060608's avatar
fxy060608 已提交
374 375 376 377 378 379 380 381
preprocessContext['MP-360'] = false
preprocessContext['MP_360'] = false
if (process.env.UNI_SUB_PLATFORM === 'mp-360') {
  preprocessContext['H5'] = false
  preprocessContext['MP-360'] = true
  preprocessContext['MP_360'] = true
}

fxy060608's avatar
fxy060608 已提交
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 465 466 467 468
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}`
  }
469 470 471 472
}

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

fxy060608's avatar
fxy060608 已提交
473 474 475 476 477 478
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
479
}
fxy060608's avatar
fxy060608 已提交
480

481
module.exports = {
fxy060608's avatar
fxy060608 已提交
482
  normalizeNodeModules,
fxy060608's avatar
fxy060608 已提交
483 484
  isInHBuilderX,
  isInHBuilderXAlpha,
fxy060608's avatar
fxy060608 已提交
485
  runByHBuilderX: isInHBuilderX || fs.existsSync(path.resolve(process.env.UNI_HBUILDERX_PLUGINS || '', 'weapp-tools')),
fxy060608's avatar
fxy060608 已提交
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 539 540 541 542
  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
  },
543 544 545
  getPlatformFilterTag () {
    return platform.filterTag
  },
fxy060608's avatar
fxy060608 已提交
546 547 548 549
  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 已提交
550 551 552
    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 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566
    if (process.env.UNI_USING_COMPONENTS) {
      return uniRuntime
    }
    return platform.vue
  },
  getPlatformCssVars () {
    return platform.cssVars
  },
  getPlatformCssnano () {
    return {
      calc: false,
      orderedValues: false,
      mergeLonghand: false,
      mergeRules: false,
fxy060608's avatar
fxy060608 已提交
567
      cssDeclarationSorter: false,
fxy060608's avatar
fxy060608 已提交
568
      uniqueSelectors: false, // 标签排序影响头条小程序
569
      minifySelectors: false, // 标签排序影响头条小程序
fxy060608's avatar
fxy060608 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
      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
fxy060608's avatar
fxy060608 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599
  },
  getBabelParserOptions () {
    return {
      sourceType: 'module',
      plugins: [
        'optionalChaining',
        'typescript',
        ['decorators', {
          decoratorsBeforeExport: true
        }],
        'classProperties'
      ]
    }
fxy060608's avatar
fxy060608 已提交
600
  }
fxy060608's avatar
fxy060608 已提交
601
}