forked from ai/size-limit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
240 lines (217 loc) · 6.27 KB
/
index.js
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
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
90
91
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
let escapeRegexp = require('escape-string-regexp')
let OptimizeCss = require('optimize-css-assets-webpack-plugin')
let Compression = require('compression-webpack-plugin')
let Analyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
let MemoryFS = require('memory-fs')
let gzipSize = require('gzip-size')
let webpack = require('webpack')
let path = require('path')
let fs = require('fs')
let os = require('os')
let promisify = require('./promisify')
const WEBPACK_EMPTY_PROJECT = {
parsed: 962,
gzip: 461
}
const STATIC =
/\.(eot|woff2?|ttf|otf|svg|png|jpe?g|gif|webp|mp4|mp3|ogg|pdf|html|ico)$/
function projectName (opts, files) {
if (opts.bundle) {
return `${ opts.bundle }.js`
} else if (files.length === 1) {
return path.basename(files[0])
} else {
return `${ path.basename(path.dirname(files[0])) }.js`
}
}
function getConfig (files, opts) {
if (opts.config) {
let config
if (path.isAbsolute(opts.config)) {
config = require(opts.config)
} else {
config = require(path.join(process.cwd(), opts.config))
}
let resolveModulesPaths = [
path.join(process.cwd(), 'node_modules')
]
if (!config.resolveLoader) config.resolveLoader = { }
if (!config.resolve) config.resolve = { }
config.resolveLoader.modules = resolveModulesPaths
config.resolve.modules = resolveModulesPaths
return config
}
let config = {
entry: files,
output: {
filename: projectName(opts, files)
},
module: {
rules: [
{
test: STATIC,
use: 'file-loader'
},
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
},
plugins: [
new OptimizeCss()
]
}
if (opts.gzip !== false) {
config.plugins.push(new Compression())
}
if (opts.ignore && opts.ignore.length !== 0) {
let escaped = opts.ignore.map(i => escapeRegexp(i))
config.externals = new RegExp(`^(${ escaped.join('|') })($|/)`)
}
if (opts.analyzer) {
config.output.path = path.join(os.tmpdir(), `size-limit-${ Date.now() }`)
config.plugins.push(new Analyzer({
openAnalyzer: opts.analyzer === 'server',
analyzerMode: opts.analyzer,
defaultSizes: opts.gzip === false ? 'parsed' : 'gzip'
}))
}
return config
}
function runWebpack (config, opts) {
return promisify(done => {
let compiler = webpack(config)
if (!opts.analyzer) {
compiler.outputFileSystem = new MemoryFS()
}
compiler.run(done)
})
}
function sumSize (s1, s2) {
return {
parsed: s1.parsed + s2.parsed,
gzip: s1.gzip + s2.gzip
}
}
function filterEntries (obj, filter) {
if (!filter) {
return obj
} else {
if (!Array.isArray(filter)) filter = [filter]
let result = { }
for (let i of filter) {
if (!obj[i]) {
throw new Error(
`Cannot find entry point ${ i } from ${ Object.keys(obj).join(', ') }`
)
}
result[i] = obj[i]
}
return result
}
}
function extractSize (stat, opts) {
let entries = filterEntries(stat.entrypoints, opts.entry)
let assets = []
Object.keys(entries).forEach(i => {
assets = assets.concat(entries[i].assets)
})
return assets.reduce((sizeInfo, assetName) => {
let parsedAsset = stat.assets.find(({ name }) => name === assetName)
let gzipAsset = stat.assets.find(({ name }) => name === `${ assetName }.gz`)
return {
parsed: sizeInfo.parsed + (parsedAsset ? parsedAsset.size : 0),
gzip: sizeInfo.gzip + (gzipAsset ? gzipAsset.size : 0)
}
}, { parsed: 0, gzip: 0 })
}
/**
* Return size of project files with all dependencies and after UglifyJS
* and gzip.
*
* @param {string|string[]} files Files to get size.
* @param {object} [opts] Extra options.
* @param {"server"|"static"|false} [opts.analyzer=false] Show package
* content in browser.
* @param {boolean} [opts.webpack=true] Pack files by webpack.
* @param {boolean} [opts.gzip=true] Compress files by gzip.
* @param {string} [opts.config] A path to custom webpack config.
* @param {string} [opts.bundle] Bundle name for Analyzer mode.
* @param {string[]} [opts.ignore] Dependencies to be ignored.
* @param {string[]} [opts.entry] Webpack entry whose size will be checked.
*
* @return {Promise} Promise with parsed and gzip size of files
*
* @example
* const getSize = require('size-limit')
*
* const index = path.join(__dirname, 'index.js')
* const extra = path.join(__dirname, 'extra.js')
*
* getSize([index, extra]).then(size => {
* if (size.gzip > 1 * 1024 * 1024) {
* console.error('Project become bigger than 1MB')
* }
* })
*/
function getSize (files, opts) {
if (typeof files === 'string') files = [files]
if (!opts) opts = { }
if (opts.webpack === false) {
return Promise.all(files.map(file => {
return promisify(done => fs.readFile(file, 'utf8', done)).then(bytes => {
if (opts.gzip === false) {
return { parsed: bytes.length, gzip: 0 }
} else {
return gzipSize(bytes).then(gzip => ({ parsed: bytes.length, gzip }))
}
})
})).then(sizes => {
let size = sizes.reduce(sumSize)
if (opts.gzip === false) {
return { parsed: size.parsed }
} else {
return size
}
})
} else {
return runWebpack(getConfig(files, opts), opts).then(stats => {
if (stats.hasErrors()) {
throw new Error(stats.toString('errors-only'))
}
let size
if (opts.config && stats.stats) {
size = stats.stats
.map(stat => extractSize(stat.toJson(), opts))
.reduce(sumSize)
} else {
size = extractSize(stats.toJson(), opts)
}
if (opts.config || opts.gzip === false) {
return {
parsed: size.parsed - WEBPACK_EMPTY_PROJECT.parsed
}
} else {
return {
parsed: size.parsed - WEBPACK_EMPTY_PROJECT.parsed,
gzip: size.gzip - WEBPACK_EMPTY_PROJECT.gzip
}
}
})
}
}
module.exports = getSize