UNPKG

2.19 kBtext/coffeescriptView Raw
1_moment = require 'moment'
2_ = require 'lodash'
3
4_utils = require './utils'
5CONSTKEY = null
6
7exports.getRawUniqueKey = (constant)->
8 #已经生成了key,并且要求返回不变的key
9 return CONSTKEY if constant and CONSTKEY
10
11 uniqueKey = _utils.config.uniqueKey
12 return "" if not uniqueKey
13 uniqueKey = '{md5}' if uniqueKey is true
14 uniqueKey = uniqueKey.replace /\{(.+)\}/g, (segment, value)->
15 switch value
16 when 'md5' then _utils.md5(new Date().toString()).substr(0, 10)
17 when 'date' then _moment().format('YYYYMMDD')
18 when 'datetime' then _moment().format('YYYYMMDDHHmmss')
19 else ''
20 #CONSTKEY只取第一次生成的key
21 CONSTKEY = uniqueKey if not CONSTKEY
22 uniqueKey
23
24#获取缓存的唯一键
25exports.getUniqueKey = (constant)->
26 uniqueKey = exports.getRawUniqueKey constant
27 uniqueKey = "?#{uniqueKey}" if uniqueKey.substr(0, 1) isnt '?'
28 uniqueKey
29
30#替换
31replaceUniqueKey = (content, rule, uniqueKey)->
32 content = content.replace(rule.firstExpr, (line, match)->
33 match += uniqueKey
34 line = line.replace rule.secondExpr, ->
35 rule.replaceTo.replace '{0}', match
36 line
37 )
38 content
39
40#css的缓存键
41cssUniqueKey = (content, uniqueKey)->
42 uniqueKey = uniqueKey || exports.getUniqueKey(true)
43 content.replace(/url\(['"]?(.+?)['"]?\)/g, (all, match)->
44 match += uniqueKey
45 return "url('#{match}')"
46 )
47
48
49#html中的缓存键img/link/script
50htmlUniqueKey = (content, uniqueKey)->
51 uniqueKey = uniqueKey || exports.getUniqueKey(true)
52
53 rules = [
54 {
55 firstExpr: /<link.+href=['"](.+?)['"].*>/g,
56 secondExpr: /href=['"](.+?)['"]/i,
57 replaceTo: "href='{0}'"
58 },{
59 firstExpr: /<script.+src=['"](.+?)['"].*>/g,
60 secondExpr: /src=['"](.+?)['"]/i,
61 replaceTo: "src='{0}'"
62 },{
63 firstExpr: /<img.+src=['"](.+?)['"].*>/g,
64 secondExpr: /src=['"](.+?)['"]/i,
65 replaceTo: "src='{0}'"
66 }
67 ]
68
69 _.map rules, (rule)-> content = replaceUniqueKey content, rule, uniqueKey
70 content
71
72#添加uniqueKey
73exports.execute = (content, type, uniqueKey)->
74 switch type
75 when 'css' then cssUniqueKey(content, uniqueKey)
76 when 'html' then htmlUniqueKey(content, uniqueKey)
77 else content
\No newline at end of file