-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathwebpack.config.js
More file actions
440 lines (418 loc) · 16.9 KB
/
webpack.config.js
File metadata and controls
440 lines (418 loc) · 16.9 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/**
* Webpack configuration file for the MHA project.
*
* This configuration file sets up various plugins and settings for building the project,
* including handling TypeScript files, CSS extraction, HTML template generation, and more.
* The configuration is environment-aware, with different optimizations for development and production.
*
* Plugins used:
* - ForkTsCheckerWebpackPlugin: Runs TypeScript type checking in a separate process.
* - HtmlWebpackPlugin: Generates HTML files for each page.
* - MiniCssExtractPlugin: Extracts CSS into separate files.
* - webpack.DefinePlugin: Defines global constants.
*
* Functions:
* - getHttpsOptions: Asynchronously retrieves HTTPS options for the development server.
* - getHash: Generates a short hash from a given string.
* - generateEntry: Generates an entry object for webpack configuration.
* - generateHtmlWebpackPlugins: Generates an array of HtmlWebpackPlugin instances for each page.
*
* Environment Variables:
* - SCM_COMMIT_ID: The commit ID used to generate a version hash.
* - APPINSIGHTS_INSTRUMENTATIONKEY: Application Insights instrumentation key.
* - npm_package_config_dev_server_port: Port for the development server.
*
* @param {Object} env - Environment variables passed to the webpack configuration.
* @param {Object} options - Options passed to the webpack configuration.
* @returns {Promise<Object>} The webpack configuration object.
*/
import path from "path";
import { fileURLToPath } from "url";
import CopyWebpackPlugin from "copy-webpack-plugin";
import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import devCerts from "office-addin-dev-certs";
import webpack from "webpack";
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Asynchronously retrieves HTTPS server options.
*
* This function attempts to get HTTPS server options using the `devCerts` library.
* If successful, it returns an object containing the certificate authority (CA),
* key, and certificate. If an error occurs, it logs the error and returns an empty object.
*
* @returns {Promise<{ca: string, key: string, cert: string} | {}>} A promise that resolves to an object with HTTPS options or an empty object if an error occurs.
*/
async function getHttpsOptions() {
try {
const httpsOptions = await devCerts.getHttpsServerOptions();
return { ca: httpsOptions.ca, key: httpsOptions.key, cert: httpsOptions.cert };
} catch (error) {
console.error("Error getting HTTPS options:", error);
return {};
}
}
/**
* Generates a hash for a given string.
* Used to reduce commit ID to something short.
*
* @param {string} str - The input string to hash.
* @returns {string} The hexadecimal representation of the hash.
*/
const getHash = (str) => {
let hash = 42;
if (str.length) {
for (let i = 0; i < str.length; i++) {
hash = Math.abs((hash << 5) - hash + str.charCodeAt(i));
}
}
return hash.toString(16);
};
const commitID = process.env.SCM_COMMIT_ID || "test";
const version = getHash(commitID);
console.log("commitID:", commitID);
console.log("version:", version);
const aikey = process.env.APPINSIGHTS_INSTRUMENTATIONKEY || "unknown";
console.log("aikey:", aikey);
const buildTime = new Date().toUTCString();
console.log("buildTime:", buildTime);
const pages = [
{ name: "mha", script: "mha" },
{ name: "uitoggle", script: "uiToggle" },
{ name: "newDesktopFrame", script: "newDesktopFrame" },
{ name: "classicDesktopFrame", script: "classicDesktopFrame" },
{ name: "newMobilePaneIosFrame", script: "newMobilePaneIosFrame" },
{ name: "privacy", script: "privacy" },
// Redirection/static pages
{ name: "Default" }, // uitoggle.html?default=classic
{ name: "DefaultPhone" }, // uitoggle.html?default=classic
{ name: "DefaultTablet" }, // uitoggle.html?default=classic
{ name: "DesktopPane" }, // uitoggle.html?default=new
{ name: "MobilePane" }, // uitoggle.html?default=new-mobile
{ name: "Functions" },
];
/**
* Generates an entry object for webpack configuration.
*
* This function iterates over a list of pages and constructs an entry object
* where each key is the name of a script and the value is the path to the
* corresponding TypeScript file.
* Entry object looks like this:
* {
* 'mha': './src/Scripts/ui/mha.ts',
* 'uiToggle': './src/Scripts/ui/uiToggle.ts',
* ...
* }
*
* @returns {Object} An object representing the entry points for webpack.
*/
function generateEntry() {
return pages.reduce((config, page) => {
if (page.script) {
config[page.script] = `./src/Scripts/ui/${page.script}.ts`;
}
return config;
}, {});
}
/**
* Generates an array of HtmlWebpackPlugin instances for each page.
* One looks like this:
* new HtmlWebpackPlugin ({
* inject: true,
* template: './src/Pages/mha.html',
* filename: 'mha.html',
* chunks: [ 'mha' ]
* })
*
* This is how our actual html files are generated, with includes for the appropriate scripts and CSS.
*
* @returns {HtmlWebpackPlugin[]} An array of HtmlWebpackPlugin instances.
*/
function generateHtmlWebpackPlugins() {
return pages.map((page) => new HtmlWebpackPlugin({
inject: true,
template: `./src/Pages/${page.name}.html`,
filename: `${page.name}.html`,
chunks: [page.script],
}));
}
export default async (env, options) => {
console.log("🚀 Starting webpack config function");
console.log("📋 env:", env);
console.log("📋 options:", options);
const isProduction = options.mode === "production";
console.log("🏭 isProduction:", isProduction);
console.log("Starting webpack.config.js - isProduction:", isProduction);
console.log("📦 Generating entry points...");
const config = {
entry: generateEntry(),
plugins: [
new MiniCssExtractPlugin({ filename: `${version}/[name].css` }),
new webpack.DefinePlugin({
__VERSION__: JSON.stringify(version),
__AIKEY__: JSON.stringify(aikey),
__BUILDTIME__: JSON.stringify(buildTime),
}),
new ForkTsCheckerWebpackPlugin(),
// Custom plugin to log compilation start/end times with timestamps
{
apply(compiler) {
compiler.hooks.watchRun.tap("TimestampPlugin", () => {
const timestamp = new Date().toISOString().replace("T", " ").substr(0, 19);
console.log(`\n🔄 [${timestamp}] WEBPACK RECOMPILATION STARTED`);
});
compiler.hooks.done.tap("TimestampPlugin", (stats) => {
const timestamp = new Date().toISOString().replace("T", " ").substr(0, 19);
const compilationTime = stats.endTime - stats.startTime;
console.log(`✅ [${timestamp}] WEBPACK RECOMPILATION COMPLETED (${compilationTime}ms)\n`);
});
compiler.hooks.invalid.tap("TimestampPlugin", (fileName) => {
const timestamp = new Date().toISOString().replace("T", " ").substr(0, 19);
console.log(`📝 [${timestamp}] FILE CHANGED: ${fileName}`);
});
}
},
new CopyWebpackPlugin({
patterns: [
{ from: "src/Resources/*", to: path.resolve(__dirname, "Resources/[name][ext]") },
{ from: "src/data/rules.json", to: path.resolve(__dirname, "Pages/data/[name][ext]") }
]
}),
...generateHtmlWebpackPlugins(),
// Bundle analyzer (when env.analyze is set)
...(env?.analyze ? [new BundleAnalyzerPlugin({
analyzerMode: "static",
openAnalyzer: false,
reportFilename: "../Pages/bundle-analysis/bundle-report.html",
})] : []),
],
mode: isProduction ? "production" : "development",
devtool: isProduction ? "source-map" : "source-map",
target: ["web", "es2022"],
module: {
rules: [
{
test: /\.tsx?$/,
use: [{
loader: "ts-loader",
options: {
logLevel: "info",
transpileOnly: true, // Let ForkTsCheckerWebpackPlugin handle type checking
experimentalWatchApi: true, // Faster incremental builds
}
}],
exclude: /node_modules/,
},
{ test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"] },
{ test: /\.js$/, enforce: "pre", use: ["source-map-loader"] },
{
test: /\.(gif|jpg|jpeg|png|svg)$/i,
type: "asset/resource",
generator: {
filename: "Resources/[name][ext]"
}
},
{
test: /\.(woff|woff2|ttf|eot)$/i,
type: "asset/resource",
generator: {
filename: "fonts/[name][ext]"
}
},
{
test: /\.json$/i,
type: "asset/resource",
generator: {
filename: "data/[name][ext]"
}
}
],
},
optimization: {
runtimeChunk: "single",
splitChunks: {
chunks: "all",
maxInitialRequests: Infinity,
minSize: 20000, // 20KB minimum chunk size
maxSize: 500000, // 500KB maximum chunk size
cacheGroups: {
// Framework libraries (React, Vue, etc. if any)
framework: {
test: /[\\/]node_modules[\\/](react|react-dom|vue|angular)[\\/]/,
name: "framework",
priority: 40,
reuseExistingChunk: true,
},
// Large libraries that should be separate
largeLibs: {
test: /[\\/]node_modules[\\/](framework7|lodash|moment|date-fns)[\\/]/,
name: "large-libs",
priority: 30,
reuseExistingChunk: true,
},
// Office/Microsoft specific libraries
office: {
test: /[\\/]node_modules[\\/](office-addin|@microsoft)[\\/]/,
name: "office-libs",
priority: 25,
reuseExistingChunk: true,
},
// Utilities and smaller libraries
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: 20,
reuseExistingChunk: true,
maxSize: 200000, // 200KB - more aggressive splitting
minSize: 30000, // 30KB minimum
},
// Common code between entry points
common: {
name: "common",
minChunks: 2,
priority: 10,
reuseExistingChunk: true,
},
// Default group for everything else
default: {
minChunks: 2,
priority: 5,
reuseExistingChunk: true,
}
}
},
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
// Improve module resolution performance
alias: {
"@": path.resolve(__dirname, "src"),
"@scripts": path.resolve(__dirname, "src/Scripts"),
"@styles": path.resolve(__dirname, "src/Content"),
},
},
output: {
filename: `${version}/[name].js`,
path: path.resolve(__dirname, "Pages"),
publicPath: "/Pages/",
clean: true,
chunkLoadingGlobal: "mhaChunkLoad",
crossOriginLoading: "anonymous",
asyncChunks: true,
compareBeforeEmit: true,
},
devServer: {
headers: {
"Access-Control-Allow-Origin": "*", // eslint-disable-line @typescript-eslint/naming-convention
"X-Content-Type-Options": "nosniff", // eslint-disable-line @typescript-eslint/naming-convention
"X-XSS-Protection": "1; mode=block", // eslint-disable-line @typescript-eslint/naming-convention
"Referrer-Policy": "no-referrer-when-downgrade", // eslint-disable-line @typescript-eslint/naming-convention
},
allowedHosts: "all", // Allow requests from any host (needed for OWA iframe)
static: {
directory: __dirname,
watch: false, // Disable watching of static files
publicPath: "/",
serveIndex: true
},
watchFiles: {
paths: [
"src/**/*.{ts,js,css}",
"src/Pages/*.html",
"src/data/rules.json"
],
options: {
ignored: [
"**/.git/**",
"**/node_modules/**",
"**/coverage/**",
"**/*.map",
"**/*.log",
"**/*.md", // Explicitly ignore markdown files
".gitignore",
".gitattributes"
],
usePolling: false,
ignoreInitial: true,
},
},
server: {
type: "https",
options: env.WEBPACK_BUILD || options.https !== undefined ? options.https : await getHttpsOptions(),
},
port: process.env.npm_package_config_dev_server_port || 44336,
compress: true, // Enable gzip compression
hot: true, // Enable hot module replacement
open: false, // Don't auto-open browser
client: {
overlay: {
errors: true,
warnings: false,
},
progress: true,
logging: "verbose", // Changed from "info" to "verbose" for more details
reconnect: 5,
},
},
stats: {
preset: "minimal",
colors: true,
timings: true,
assets: false,
chunks: false,
modules: false,
children: false,
warnings: true,
errors: true,
errorDetails: true,
logging: "info",
loggingDebug: ["webpack.Progress"],
},
infrastructureLogging: {
level: "info",
debug: false,
},
};
console.log("⚙️ Main config object created successfully");
// Production-specific optimizations
if (isProduction) {
console.log("🏭 Applying production optimizations...");
// Remove console.log statements in production
config.optimization.minimizer = [
"...",
new webpack.DefinePlugin({
// eslint-disable-next-line @typescript-eslint/naming-convention
"console.log": "void 0",
})
];
// Add performance budgets with more realistic limits for chunked bundles
config.performance = {
maxAssetSize: 500000, // 500KB per asset (more realistic with chunking)
maxEntrypointSize: 1000000, // 1MB per entry point (reduced from 1.5MB)
hints: "warning",
};
// Production-specific optimization
config.optimization.usedExports = true;
config.optimization.sideEffects = false;
} else {
console.log("🛠️ Applying development optimizations...");
// Development-specific optimizations
config.cache = {
type: "filesystem",
buildDependencies: {
config: [__filename],
},
};
// Faster source map generation in development
config.module.rules.forEach(rule => {
if (rule.enforce === "pre" && rule.use && rule.use.includes("source-map-loader")) {
rule.exclude = /node_modules/;
}
});
}
console.log("🎯 Webpack config completed successfully");
return config;
};