forked from ai/size-limit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
193 lines (174 loc) · 5.13 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
'use strict'
const escapeRegexp = require('escape-string-regexp')
const Compression = require('compression-webpack-plugin')
const Analyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const MemoryFS = require('memory-fs')
const gzipSize = require('gzip-size')
const webpack = require('webpack')
const Uglify = require('uglifyjs-webpack-plugin')
const path = require('path')
const fs = require('fs')
const os = require('os')
const promisify = require('./promisify')
const WEBPACK_EMPTY_PROJECT = 293
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
/* eslint-disable global-require, security/detect-non-literal-require */
if (path.isAbsolute(opts.config)) {
config = require(opts.config)
} else {
config = require(path.join(process.cwd(), opts.config))
}
/* eslint-enable global-require, security/detect-non-literal-require */
// resolve relative node_modules
const resolveModulesPaths = [
path.join(process.cwd(), 'node_modules')
]
config.resolveLoader = { modules: resolveModulesPaths }
config.resolve = { modules: resolveModulesPaths }
return config
}
const config = {
entry: files,
output: {
filename: projectName(opts, files)
},
module: {
rules: [
{
test: STATIC,
use: 'file-loader'
},
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
minimize: true
}
}
]
},
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
minimize: true,
modules: true
}
}
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new Uglify({ sourceMap: false }),
new Compression({ asset: '[path].gz' })
]
}
if (opts.ignore) {
const escaped = opts.ignore.map(i => escapeRegexp(i))
// eslint-disable-next-line security/detect-non-literal-regexp
const regexp = new RegExp(`^(${ escaped.join('|') })($|/)`)
config.plugins.push(new webpack.IgnorePlugin(regexp))
}
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: 'gzip'
}))
}
return config
}
function runWebpack (config, opts) {
return promisify(done => {
const compiler = webpack(config)
if (!opts.analyzer) {
compiler.outputFileSystem = new MemoryFS()
}
compiler.run(done)
})
}
function extractSize (stat, opts) {
let name = stat.compilation.outputOptions.filename
name += opts.config ? '' : '.gz'
const assets = stat.toJson().assets
return assets.find(i => i.name === name).size
}
/**
* 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 {true|false} [opts.webpack=true] Pack files by webpack.
* @param {string} [opts.bundle] Bundle name for Analyzer mode.
* @param {string[]} [opts.ignore] Dependencies to be ignored.
*
* @return {Promise} Promise with 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 > 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 => {
return gzipSize(bytes)
})
})).then(sizes => {
return sizes.reduce((all, size) => all + size, 0)
})
} else {
return runWebpack(getConfig(files, opts), opts).then(stats => {
if (stats.hasErrors()) {
throw new Error(stats.toString('errors-only'))
}
let size
// unwrap from resolved if configuration requires it
if (opts.config && stats.stats) {
size = stats.stats.reduce((pre, cur) => pre + extractSize(cur, opts), 0)
} else {
size = extractSize(stats, opts)
}
return size - WEBPACK_EMPTY_PROJECT
})
}
}
module.exports = getSize