1
1
var eslint = require ( "eslint" )
2
2
var assign = require ( "object-assign" )
3
3
var loaderUtils = require ( "loader-utils" )
4
+ var crypto = require ( "crypto" )
5
+ var fs = require ( "fs" )
6
+ var findCacheDir = require ( "find-cache-dir" )
7
+
8
+ var engine = null
9
+ var cache = null
10
+ var cachePath = null
4
11
5
12
/**
6
13
* linter
@@ -11,8 +18,6 @@ var loaderUtils = require("loader-utils")
11
18
* @return {void }
12
19
*/
13
20
function lint ( input , config , webpack ) {
14
- var engine = new eslint . CLIEngine ( config )
15
-
16
21
var resourcePath = webpack . resourcePath
17
22
var cwd = process . cwd ( )
18
23
@@ -22,7 +27,30 @@ function lint(input, config, webpack) {
22
27
resourcePath = resourcePath . substr ( cwd . length + 1 )
23
28
}
24
29
25
- var res = engine . executeOnText ( input , resourcePath , true )
30
+ var res
31
+ // If cache is enable and the data are the same as in the cache, just
32
+ // use them
33
+ if ( config . cache ) {
34
+ var inputMD5 = crypto . createHash ( "md5" ) . update ( input ) . digest ( "hex" )
35
+ if ( cache [ resourcePath ] && cache [ resourcePath ] . hash === inputMD5 ) {
36
+ res = cache [ resourcePath ] . res
37
+ }
38
+ }
39
+
40
+ // Re-lint the text if the cache off or miss
41
+ if ( ! res ) {
42
+ res = engine . executeOnText ( input , resourcePath , true )
43
+
44
+ // Save new results in the cache
45
+ if ( config . cache ) {
46
+ cache [ resourcePath ] = {
47
+ hash : inputMD5 ,
48
+ res : res ,
49
+ }
50
+ fs . writeFileSync ( cachePath , JSON . stringify ( cache ) )
51
+ }
52
+ }
53
+
26
54
// executeOnText ensure we will have res.results[0] only
27
55
28
56
// skip ignored file warning
@@ -108,6 +136,33 @@ module.exports = function(input, map) {
108
136
loaderUtils . parseQuery ( this . query )
109
137
)
110
138
this . cacheable ( )
139
+
140
+ // Create the engine only once
141
+ if ( engine === null ) {
142
+ engine = new eslint . CLIEngine ( config )
143
+ }
144
+
145
+ // Read the cached information only once and if enable
146
+ if ( cache === null ) {
147
+ if ( config . cache ) {
148
+ var thunk = findCacheDir ( {
149
+ name : "eslint-loader" ,
150
+ thunk : true ,
151
+ create : true ,
152
+ } )
153
+ cachePath = thunk ( "data.json" )
154
+ try {
155
+ cache = require ( cachePath )
156
+ }
157
+ catch ( e ) {
158
+ cache = { }
159
+ }
160
+ }
161
+ else {
162
+ cache = false
163
+ }
164
+ }
165
+
111
166
lint ( input , config , this )
112
167
this . callback ( null , input , map )
113
168
}
0 commit comments