cache-loader.js 1.9 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 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 60 61 62 63 64
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const BJSON = require('buffer-json')

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

const directories = new Set()

function write (key, data, callback) {
  const dirname = path.dirname(key)
  // template,缓存 mp template
  if (
    data.remainingRequest.indexOf('vue&type=template') !== -1 &&
    process.UNI_CACHE_TEMPLATES
  ) {
    data['mpTemplates'] = process.UNI_CACHE_TEMPLATES
    delete process.UNI_CACHE_TEMPLATES
  }

  const content = BJSON.stringify(data)

  if (directories.has(dirname)) {
    // for performance skip creating directory
    fs.writeFile(key, content, 'utf-8', callback)
  } else {
    mkdirp(dirname, (mkdirErr) => {
      if (mkdirErr) {
        callback(mkdirErr)
        return
      }

      directories.add(dirname)

      fs.writeFile(key, content, 'utf-8', callback)
    })
  }
}

function read (key, callback) {
  fs.readFile(key, 'utf-8', (err, content) => {
    if (err) {
      callback(err)
      return
    }

    try {
      const data = BJSON.parse(content)
      const mpTemplates = data['mpTemplates']
      if (mpTemplates) {
        Object.keys(mpTemplates).forEach(name => {
          fs.writeFileSync(name, mpTemplates[name], 'utf-8')
        })
      }
      callback(null, data)
    } catch (e) {
      callback(e)
    }
  })
}

module.exports = {
fxy060608's avatar
fxy060608 已提交
65
  createTemplateCacheLoader: function (api, id = 'uni-template-compiler') {
fxy060608's avatar
fxy060608 已提交
66 67 68 69 70 71
    return {
      resourceQuery: /type=uni-cache-loader-template/,
      use: [{
        loader: 'cache-loader',
        ident: 'uni-cache-loader-template-options',
        options: Object.assign(api.genCacheConfig(
fxy060608's avatar
fxy060608 已提交
72
          id + '/' + process.env.UNI_PLATFORM,
fxy060608's avatar
fxy060608 已提交
73 74 75 76 77 78 79 80 81
          getPartialIdentifier()
        ), {
          read,
          write
        })
      }]
    }
  }
}