platform.js 14.0 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
init v3  
fxy060608 已提交
30 31 32 33 34 35 36 37
  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 已提交
38 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
  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,
90
    megalo: false,
fxy060608's avatar
fxy060608 已提交
91
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    subPackages: false,
    cssVars: {
      '--status-bar-height': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
      return [
        ...getStaticCopyOptions(assetsDir),
        {
          from: require.resolve('@dcloudio/uni-h5/dist/index.css'),
          to: assetsDir,
          transform (content) {
            if (process.env.NODE_ENV === 'production') {
              return content + getShadowCss()
            }
            return content
          }
        },
        ...getCopyOptions(['hybrid/html'])
      ]
    }
  },
  'app-plus': {
    global: 'wx',
    exts: {
      style: '.wxss',
119 120
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
121 122 123 124
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
125
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
126 127 128 129 130 131 132 133 134
    subPackages: false,
    cssVars: {
      '--window-top': '0px',
      '--window-bottom': '0px'
    },
    copyWebpackOptions ({
      assetsDir
    }) {
      const files = ['hybrid/html']
135
      let wxcomponents = []
fxy060608's avatar
init v3  
fxy060608 已提交
136
      if (!process.env.UNI_USING_NATIVE && !process.env.UNI_USING_V3) {
137 138 139
        wxcomponents = getCopyOptions(['wxcomponents'], {
          to: path.resolve(process.env.UNI_OUTPUT_TMP_DIR, 'wxcomponents')
        })
fxy060608's avatar
fxy060608 已提交
140
      }
fxy060608's avatar
init v3  
fxy060608 已提交
141 142 143 144
      let template = []
      if (process.env.UNI_USING_V3) {
        template = getCopyOptions([path.resolve(__dirname, '../template')])
      }
fxy060608's avatar
fxy060608 已提交
145
      return [
fxy060608's avatar
init v3  
fxy060608 已提交
146
        ...template,
fxy060608's avatar
fxy060608 已提交
147
        ...getStaticCopyOptions(assetsDir),
148
        ...wxcomponents,
fxy060608's avatar
fxy060608 已提交
149 150 151 152 153 154 155 156
        ...getCopyOptions(files)
      ]
    }
  },
  'mp-qq': {
    global: 'wx',
    exts: {
      style: '.qss',
157 158
      template: '.qml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
159 160 161 162
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
163
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    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',
184 185
      template: '.wxml',
      filter: '.wxs'
fxy060608's avatar
fxy060608 已提交
186 187 188 189
    },
    vue: mpvueRuntime,
    compiler: mpvueCompiler,
    megalo: false,
190
    filterTag: 'wxs',
fxy060608's avatar
fxy060608 已提交
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 218 219 220
    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',
221 222
      template: '.swan',
      filter: '.filter.js'
fxy060608's avatar
fxy060608 已提交
223 224 225 226
    },
    vue: megaloRuntime,
    compiler: megaloCompiler,
    megalo: 'swan',
227
    filterTag: 'filter',
fxy060608's avatar
fxy060608 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    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',
248 249
      template: '.axml',
      filter: '.sjs'
fxy060608's avatar
fxy060608 已提交
250 251 252 253
    },
    vue: megaloRuntime,
    compiler: megaloCompiler,
    megalo: 'alipay',
fxy060608's avatar
fxy060608 已提交
254
    filterTag: 'sjs',
fxy060608's avatar
fxy060608 已提交
255
    subPackages: true,
fxy060608's avatar
fxy060608 已提交
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 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
    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}`
  }
419 420 421 422
}

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

fxy060608's avatar
fxy060608 已提交
423 424 425 426 427 428
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
429
}
fxy060608's avatar
fxy060608 已提交
430

431
module.exports = {
fxy060608's avatar
fxy060608 已提交
432
  normalizeNodeModules,
fxy060608's avatar
fxy060608 已提交
433 434
  isInHBuilderX,
  isInHBuilderXAlpha,
fxy060608's avatar
fxy060608 已提交
435
  runByHBuilderX: isInHBuilderX || fs.existsSync(path.resolve(process.env.UNI_HBUILDERX_PLUGINS || '', 'weapp-tools')),
fxy060608's avatar
fxy060608 已提交
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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
  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
  },
493 494 495
  getPlatformFilterTag () {
    return platform.filterTag
  },
fxy060608's avatar
fxy060608 已提交
496 497 498 499
  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 已提交
500 501 502
    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 已提交
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
    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
  }
}