-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
297 lines (270 loc) · 8.17 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
const path = require('node:path')
const webpack = require('webpack')
const createBabelConfig = require('./babel.config')
const defaultProjectRoot = process.cwd()
class WebpackConfigBuilder {
/**
* @param {WebpackBuilderParams} params
* @constructor
*/
constructor(params) {
this.params = { //apply default params
define: {},
projectRoot: defaultProjectRoot,
outputPath: './lib',
gatherBundleStats: false,
sourcemap: true,
...params
}
this.params.outputPath = this.ensureAbsolutePath(this.params.outputPath)
Object.freeze(this.params)
}
/**
* @type {WebpackBuilderParams}
*/
params
/**
* @type {{}[]}
* @private
*/
plugins
/**
* @type {'development'|'production'}
*/
mode
get isProduction() {
return this.mode !== 'development'
}
build(env, argv) {
const mode = this.mode = argv.mode || 'development'
process.env.NODE_ENV = mode
console.log('Building webpack project ' + this.params.projectRoot)
console.log('mode=' + mode)
//plugins
this.plugins = []
this.initProvidePlugin()
this.initIgnorePlugin()
this.initLoaderOptionsPlugin()
this.initDefinePlugin()
this.initBundleAnalyzerPlugin()
const res = {
mode,
entry: this.prepareEntry(),
output: this.prepareOutput(),
module: {
rules: this.prepareModuleRules(),
noParse: /\.wasm$/
},
plugins: this.plugins,
externals: this.prepareExternals(),
resolve: this.prepareResolveSection(),
resolveLoader: {
modules: ['node_modules', path.resolve(__dirname, 'node_modules')]
},
optimization: {
moduleIds: 'deterministic',
minimizer: this.prepareMinimizerSection()
},
devtool: this.prepareSourceMapSection()
}
return res
}
/**
* @private
*/
ensureAbsolutePath(value) {
return path.isAbsolute(value) ?
value :
path.resolve(this.params.projectRoot, value)
}
/**
* @private
*/
prepareModuleRules() {
return [
{
test: /\.js?$/,
loader: 'babel-loader'
},
{
test: /\.wasm$/,
loader: 'base64-loader',
type: 'javascript/auto'
}
]
}
prepareExternals() {
const res = {
'@stellar/stellar-sdk': '@stellar/stellar-sdk',
'@stellar/stellar-base': '@stellar/stellar-base'
}
if (this.params.externals) {
Object.assign(res, this.params.externals)
}
return res
}
/**
* @private
*/
prepareMinimizerSection() {
if (!this.isProduction)
return
const TerserPlugin = require('terser-webpack-plugin')
return [
new TerserPlugin({
terserOptions: {
//warnings: true,
toplevel: true
}
})
]
}
/**
* @private
*/
prepareEntry() {
const {libName, inputPath} = this.params
if (!libName || !inputPath)
throw new Error('No entries to process')
return {[libName]: this.ensureAbsolutePath(inputPath)}
}
/**
* @private
*/
prepareOutput() {
const {libName, outputPath, globalObject = 'globalThis', entry, library} = this.params
const libProps = Object.assign({
name: libName,
type: 'umd2',
export: 'default'
}, library)
return {
path: this.ensureAbsolutePath(outputPath),
filename: '[name].js',
library: libProps,
globalObject,
clean: true
}
}
/**
* @private
*/
prepareSourceMapSection() {
if (this.params.sourcemap !== false)
return 'source-map'
}
/**
* @private
*/
initIgnorePlugin() {
const {ignoreCallback} = this.params
if (ignoreCallback) {
this.plugins.push(new webpack.IgnorePlugin({
checkResource(resource, context) {
if (ignoreCallback && ignoreCallback(resource, context))
return true
return false
}
}))
}
}
/**
* @private
*/
initProvidePlugin() {
this.plugins.push(new webpack.ProvidePlugin({Buffer: ['buffer', 'Buffer']}))
}
/**
* @private
*/
initLoaderOptionsPlugin() {
this.plugins.unshift(new webpack.LoaderOptionsPlugin({
minimize: !!this.isProduction,
debug: false,
sourceMap: this.params.sourcemap
}))
}
/**
* @private
*/
initDefinePlugin() {
const {define = {}} = this.params
const vars = {'process.env.NODE_ENV': JSON.stringify(this.mode)}
for (const [key, value] of Object.entries(define)) {
vars[key] = JSON.stringify(value)
}
this.plugins.push(new webpack.DefinePlugin(vars))
}
/**
* @private
*/
initBundleAnalyzerPlugin() {
if (!this.params.gatherBundleStats)
return
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
this.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'bundle-stats.html',
openAnalyzer: false
}))
try { //optional duplicates analysis
const inspectpack = require('inspectpack/plugin')
if (!inspectpack) return
this.plugins.push(new inspectpack.DuplicatesPlugin({
emitErrors: false,
ignoredPackages: []
}))
} catch (e) {
}
}
/**
* @private
*/
prepareResolveSection() {
return {
symlinks: true, //important for PNPM
modules: [path.resolve(this.params.projectRoot, 'node_modules'), 'node_modules'],
fallback: {
util: false,
http: false,
https: false,
path: false,
fs: false,
url: false,
events: require.resolve('events'),
buffer: require.resolve('buffer/'),
stream: require.resolve('stream-browserify')
}
}
}
}
/**
* Init webpack configuration function
* @param {WebpackBuilderParams} params
* @return {Function}
*/
function initLibWebpackConfig(params) {
const builder = new WebpackConfigBuilder(params)
return builder.build.bind(builder)
}
module.exports = {initLibWebpackConfig, createBabelConfig}
/**
* @typedef {{}} WebpackBuilderParams
* @property {String} libName - Library name (in camelCase)
* @property {String} inputPath - Input file path ('./index.js' by default)
* @property {String} outputPath - Output base path (relative or absolute path)
* @property {String} [projectRoot] - Project root directory
* @property {LibraryProps} [library] - Library properties (default value is {type: 'umd2', export: 'default'})
* @property {{}} [define] - Additional variables to be defined in the execution scope
* @property {{}} [externals] - External libraries that should be excluded from the bundle
* @property {Boolean} [sourcemap] - Generate source map (always generated by default)
* @property {String} [globalObject] - Global object reference (globalThis by default)
* @property {Function} [ignoreCallback] - Callback to use for ignoring packages bundled to the output
* @property {Boolean} [gatherBundleStats] - Generate bundle stats report on production builds
*/
/**
* @typedef {{}} LibraryProps
* @property {String} [name] - Library output variable name (if omitted, entry[0] is used)
* @property {String} [type] - Library target ('umd2' by default)
* @property {String} [export] - Name of the default export ('default' by default)
*/