-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
webpack.config.ts
361 lines (339 loc) · 11.5 KB
/
webpack.config.ts
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import Path from 'path';
import Fs from 'fs';
import { stringifyRequest } from 'loader-utils';
import webpack from 'webpack';
// @ts-expect-error
import TerserPlugin from 'terser-webpack-plugin';
import webpackMerge from 'webpack-merge';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import UiSharedDepsNpm from '@kbn/ui-shared-deps-npm';
import * as UiSharedDepsSrc from '@kbn/ui-shared-deps-src';
import StatoscopeWebpackPlugin from '@statoscope/webpack-plugin';
// @ts-expect-error
import VisualizerPlugin from 'webpack-visualizer-plugin2';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { Bundle, BundleRemotes, WorkerConfig, parseDllManifest } from '../common';
import { BundleRemotesPlugin } from './bundle_remotes_plugin';
import { BundleMetricsPlugin } from './bundle_metrics_plugin';
import { EmitStatsPlugin } from './emit_stats_plugin';
import { PopulateBundleCachePlugin } from './populate_bundle_cache_plugin';
const BABEL_PRESET = require.resolve('@kbn/babel-preset/webpack_preset');
const DLL_MANIFEST = JSON.parse(Fs.readFileSync(UiSharedDepsNpm.dllManifestPath, 'utf8'));
export function getWebpackConfig(
bundle: Bundle,
bundleRemotes: BundleRemotes,
worker: WorkerConfig
) {
const ENTRY_CREATOR = require.resolve('./entry_point_creator');
const commonConfig: webpack.Configuration = {
node: { fs: 'empty' },
context: bundle.contextDir,
cache: true,
entry: {
[bundle.id]: ENTRY_CREATOR,
},
devtool: worker.dist ? false : '#cheap-source-map',
profile: worker.profileWebpack,
output: {
hashFunction: 'sha1',
path: bundle.outputDir,
filename: `${bundle.id}.${bundle.type}.js`,
chunkFilename: `${bundle.id}.chunk.[id].js`,
devtoolModuleFilenameTemplate: (info) =>
`/${bundle.type}:${bundle.id}/${Path.relative(
bundle.sourceRoot,
info.absoluteResourcePath
)}${info.query}`,
jsonpFunction: `${bundle.id}_bundle_jsonpfunction`,
},
optimization: {
noEmitOnErrors: true,
splitChunks: {
maxAsyncRequests: 10,
cacheGroups: {
default: {
reuseExistingChunk: false,
},
},
},
},
externals: UiSharedDepsSrc.externals,
plugins: [
new CleanWebpackPlugin(),
new BundleRemotesPlugin(bundle, bundleRemotes),
new PopulateBundleCachePlugin(worker, bundle, parseDllManifest(DLL_MANIFEST)),
new BundleMetricsPlugin(bundle),
new webpack.DllReferencePlugin({
context: worker.repoRoot,
manifest: DLL_MANIFEST,
}),
// @ts-ignore something is wrong with the StatoscopeWebpackPlugin type.
...(worker.profileWebpack
? [
new EmitStatsPlugin(bundle),
new StatoscopeWebpackPlugin({
open: false,
saveReportTo: `${bundle.outputDir}/${bundle.id}.statoscope.html`,
}),
new VisualizerPlugin({ filename: `${bundle.id}.visualizer.html` }),
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: `${bundle.id}.analyzer.html`,
openAnalyzer: false,
logLevel: 'silent',
}),
]
: []),
// @ts-ignore something is wrong with the StatoscopeWebpackPlugin type.
...(bundle.banner ? [new webpack.BannerPlugin({ banner: bundle.banner, raw: true })] : []),
],
module: {
// no parse rules for a few known large packages which have no require() statements
// or which have require() statements that should be ignored because the file is
// already bundled with all its necessary dependencies
noParse: [
/[\/\\]node_modules[\/\\]lodash[\/\\]index\.js$/,
/[\/\\]node_modules[\/\\]vega[\/\\]build-es5[\/\\]vega\.js$/,
],
rules: [
{
include: [ENTRY_CREATOR],
use: [
{
loader: UiSharedDepsNpm.publicPathLoader,
options: {
key: bundle.id,
},
},
{
loader: require.resolve('val-loader'),
options: {
entries: bundle.remoteInfo.targets.map((target) => {
const absolute = Path.resolve(bundle.contextDir, target);
const newContext = Path.dirname(ENTRY_CREATOR);
const importId = `${bundle.type}/${bundle.id}/${target}`;
// relative path from context of the ENTRY_CREATOR, with linux path separators
let requirePath = Path.relative(newContext, absolute).split('\\').join('/');
if (!requirePath.startsWith('.')) {
// ensure requirePath is identified by node as relative
requirePath = `./${requirePath}`;
}
return { importId, requirePath };
}),
},
},
],
},
{
test: /\.css$/,
include: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: !worker.dist,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: !worker.dist,
postcssOptions: {
config: require.resolve('../../postcss.config.js'),
},
},
},
],
},
{
test: /\.scss$/,
exclude: /node_modules/,
oneOf: [
...worker.themeTags.map((theme) => ({
resourceQuery: `?${theme}`,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: !worker.dist,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: !worker.dist,
postcssOptions: {
config: require.resolve('../../postcss.config.js'),
},
},
},
{
loader: 'sass-loader',
options: {
additionalData(content: string, loaderContext: webpack.loader.LoaderContext) {
return `@import ${stringifyRequest(
loaderContext,
Path.resolve(
worker.repoRoot,
`src/core/public/styles/core_app/_globals_${theme}.scss`
)
)};\n${content}`;
},
implementation: require('sass-embedded'),
sassOptions: {
outputStyle: worker.dist ? 'compressed' : 'expanded',
includePaths: [Path.resolve(worker.repoRoot, 'node_modules')],
sourceMap: true,
quietDeps: true,
},
},
},
],
})),
{
loader: require.resolve('./theme_loader'),
options: {
bundleId: bundle.id,
themeTags: worker.themeTags,
},
},
],
},
{
test: /\.(woff|woff2|ttf|eot|svg|ico|png|jpg|gif|jpeg)(\?|$)/,
loader: 'url-loader',
options: {
limit: 8192,
},
},
{
test: /\.(js|tsx?)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
babelrc: false,
envName: worker.dist ? 'production' : 'development',
presets: [BABEL_PRESET],
},
},
},
{
test: /node_modules\/@?xstate5\/.*\.js$/,
use: {
loader: 'babel-loader',
options: {
babelrc: false,
envName: worker.dist ? 'production' : 'development',
presets: [BABEL_PRESET],
plugins: ['@babel/plugin-transform-logical-assignment-operators'],
},
},
},
{
test: /\.js$/,
include: /node_modules[\\\/]@dagrejs/,
use: {
loader: 'babel-loader',
options: {
envName: worker.dist ? 'production' : 'development',
presets: ['@babel/preset-env'], // Doesn't work with BABEL_PRESET
plugins: ['@babel/plugin-proposal-class-properties'],
},
},
},
{
test: /node_modules[\/\\]@?xyflow[\/\\].*.js$/,
loaders: 'babel-loader',
options: {
envName: worker.dist ? 'production' : 'development',
presets: [BABEL_PRESET],
plugins: ['@babel/plugin-transform-logical-assignment-operators'],
},
},
{
test: /node_modules[\/\\]launchdarkly[^\/\\]+[\/\\].*.js$/,
loaders: 'babel-loader',
options: {
envName: worker.dist ? 'production' : 'development',
presets: [BABEL_PRESET],
},
},
{
test: /\.(html|md|txt|tmpl)$/,
use: {
loader: 'raw-loader',
},
},
{
test: /\.peggy$/,
loader: require.resolve('@kbn/peggy-loader'),
},
],
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.json'],
mainFields: ['browser', 'main'],
alias: {
core_app_image_assets: Path.resolve(
worker.repoRoot,
'src/core/public/styles/core_app/images'
),
vega: Path.resolve(worker.repoRoot, 'node_modules/vega/build-es5/vega.js'),
'react-dom$':
worker.reactVersion === '18' ? 'react-dom-18/profiling' : 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
react: worker.reactVersion === '18' ? 'react-18' : 'react',
},
},
performance: {
// NOTE: we are disabling this as those hints
// are more tailored for the final bundles result
// and not for the webpack compilations performance itself
hints: false,
},
};
const nonDistributableConfig: webpack.Configuration = {
mode: 'development',
};
const distributableConfig: webpack.Configuration = {
mode: 'production',
plugins: [
new webpack.DefinePlugin({
'process.env': {
IS_KIBANA_DISTRIBUTABLE: `"true"`,
},
}),
],
optimization: {
minimizer: [
new TerserPlugin({
cache: false,
sourceMap: false,
extractComments: false,
parallel: false,
terserOptions: {
compress: { passes: 2 },
keep_classnames: true,
mangle: true,
},
}),
],
},
};
return webpackMerge(commonConfig, worker.dist ? distributableConfig : nonDistributableConfig);
}