patch.js 1.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
const fs = require('fs-extra')

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

fxy060608's avatar
fxy060608 已提交
7
const VANT_ASSETS = [{ // wxs array.constructor
fxy060608's avatar
fxy060608 已提交
8 9 10 11 12 13
  test(src) {
    return src.indexOf('array.wxs') !== -1
  },
  source(code) {
    return code.replace(`array.constructor === 'Array'`, 'Array.isArray(array)')
  }
fxy060608's avatar
fxy060608 已提交
14 15 16 17 18 19 20 21 22
}]

const PATCH_ASSETS = [
  ...VANT_ASSETS
]

const VANT_VUES = [{
  test(file) {
    return normalizePath(file.path).indexOf('/image/index.vue') !== -1
fxy060608's avatar
fxy060608 已提交
23 24
  },
  source(code) {
fxy060608's avatar
fxy060608 已提交
25 26 27
    // onLoad 与 onError 是生命周期函数名,需要替换为其他
    return code.replace(/onLoad/g, 'onImageLoad')
      .replace(/onError/g, 'onImageError')
fxy060608's avatar
fxy060608 已提交
28
  }
fxy060608's avatar
fxy060608 已提交
29
}]
fxy060608's avatar
fxy060608 已提交
30

fxy060608's avatar
fxy060608 已提交
31 32
const PATCH_VUES = [
  ...VANT_VUES
fxy060608's avatar
fxy060608 已提交
33 34
]

fxy060608's avatar
fxy060608 已提交
35 36
function patchAsset(src, dest) {
  const options = PATCH_ASSETS.find(patch => patch.test(src))
fxy060608's avatar
fxy060608 已提交
37 38 39 40 41 42
  if (options) {
    console.log(`write: ${dest}`)
    fs.outputFileSync(dest, options.source(fs.readFileSync(src).toString()))
    return true
  }
  return false
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47 48 49 50 51
}

function patchVue(file) {
  const options = PATCH_VUES.find(patch => patch.test(file))
  if (options) {
    file.content = options.source(file.content)
  }
}

fxy060608's avatar
fxy060608 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
const VANT_WRAPPERS = [
  function test(filepath) {
    return filepath.indexOf('/cell/index') !== -1
  },
  function test(filepath) {
    return filepath.indexOf('/sticky/index') !== -1
  }
]

const PATCH_WRAPPERS = [
  ...VANT_WRAPPERS
]

function patchWrapper(filepath) {
  filepath = normalizePath(filepath)
  return !!PATCH_WRAPPERS.find(test => test(filepath))
}

fxy060608's avatar
fxy060608 已提交
70 71
module.exports = {
  vue: patchVue,
fxy060608's avatar
fxy060608 已提交
72 73
  asset: patchAsset,
  wrapper: patchWrapper
fxy060608's avatar
fxy060608 已提交
74
}