Repository navigation
Expand file tree
/
Copy pathwebpack.config.js
More file actions
288 lines (280 loc) · 10.6 KB
/
Copy pathwebpack.config.js
File metadata and controls
288 lines (280 loc) · 10.6 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
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
const isAnalyze = process.env.ANALYZE === 'true';
// FIX: Use USE_DEV_SERVER to match package.json scripts
const isDevServer = process.env.USE_DEV_SERVER === 'true';
return {
mode: argv.mode || 'development',
// Name the entry `renderer` so `output.filename: '[name].js'` emits
// `dist/renderer.js`. An unnamed array entry defaults to chunk name `main`,
// which would overwrite Electron's `dist/main.js` from webpack.main.config.js.
entry: {
renderer: ['./src/renderer/polyfills.js', './src/renderer/index.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
// Sync entry -> `renderer.js`; splitChunks / async chunks use [name].[id].js.
filename: '[name].js',
// Numeric ids for anonymous async chunks keep bundle diffs stable;
// named chunks (phase imports, vendors) win via [name] when set.
chunkFilename: '[name].[id].js',
// FIX: Use './' for Electron file:// protocol compatibility
publicPath: './',
globalObject: 'globalThis'
},
target: 'web',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
// Keep this in lock-step with the `electron` devDep in
// `package.json`. Electron 45 ships Chromium 156 /
// Node 24, so a lower target forces needless polyfills
// and transforms for syntax that the real runtime
// already supports natively.
targets: { electron: '45.0' }
}
],
'@babel/preset-react'
],
plugins: [...(isDevServer ? ['react-refresh/babel'] : [])]
}
}
},
{
test: /\.css$/,
use: [
// FIX: Use style-loader in dev for HMR, MiniCssExtractPlugin in prod
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
'css-loader',
'postcss-loader'
]
},
// FIX: Add asset loader rules for SVG, images, and fonts
{
test: /\.svg$/,
oneOf: [
{
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack'],
type: 'javascript/auto'
},
{
type: 'asset/resource',
generator: {
filename: 'images/[name][ext]'
}
}
]
},
{
test: /\.(png|jpg|jpeg|gif|webp)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[name][ext]'
}
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'fonts/[name][ext]'
}
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.mjs', '.cjs', '.json'],
// FIX: Use consistent fallbacks for both dev and prod to avoid module resolution issues
// Redux Toolkit and other modern libraries require process polyfill
// Note: crypto fallback disabled - renderer uses native Web Crypto API instead
fallback: {
path: require.resolve('path-browserify'),
os: require.resolve('os-browserify/browser'),
crypto: false,
buffer: require.resolve('buffer'),
process: require.resolve('process/browser'),
stream: require.resolve('stream-browserify'),
util: require.resolve('util'),
url: require.resolve('url'),
querystring: require.resolve('querystring-es3'),
assert: require.resolve('assert'),
events: require.resolve('events'),
fs: false,
child_process: false,
worker_threads: false,
async_hooks: false,
vm: false
}
},
externals: {},
plugins: [
new HtmlWebpackPlugin({
template: './src/renderer/index.html',
filename: 'index.html',
inject: true,
scriptLoading: 'defer'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development'),
global: 'globalThis'
}),
// FIX: Use resolved path for process polyfill to avoid module resolution issues
new webpack.ProvidePlugin({
process: require.resolve('process/browser'),
Buffer: ['buffer', 'Buffer']
}),
// FIX: Ignore Node.js specific modules in renderer build to suppress warnings
// correlationId.js handles missing modules gracefully
new webpack.IgnorePlugin({
// `perf_hooks` is referenced from a try/catch guarded require inside
// shared/perfMarks.js so it works in main + tests. The renderer
// bundle never needs the node module (performance is on
// globalThis); ignoring it keeps the warning log clean.
resourceRegExp: /^(async_hooks|crypto|perf_hooks)$/
}),
// FIX: Only extract CSS in production mode (dev uses style-loader for HMR)
...(isProduction ? [new MiniCssExtractPlugin({ filename: 'styles.css' })] : []),
// FIX: Use isDevServer variable for consistency
...(isDevServer ? [new ReactRefreshWebpackPlugin({ overlay: false })] : []),
...(isAnalyze ? [new BundleAnalyzerPlugin({ analyzerMode: 'static' })] : [])
],
// Use CSP-compliant devtool: 'source-map' generates separate .map files
// without eval(), satisfying script-src 'self' in createWindow.js CSP.
devtool: isProduction ? false : 'source-map',
// Development server configuration
devServer: isProduction
? undefined
: {
static: {
directory: path.join(__dirname, 'dist')
},
compress: true,
port: 3000,
hot: true,
// Security headers
headers: {
'Content-Security-Policy':
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' ws://localhost:*; object-src 'none'; base-uri 'self'; form-action 'self';"
}
},
// Performance optimizations
performance: {
hints: isProduction ? 'warning' : false,
maxEntrypointSize: 5120000, // 5MB (relaxed for Electron/Desktop)
maxAssetSize: 5120000 // 5MB
},
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
},
cacheDirectory: path.resolve(__dirname, '.webpack-cache')
},
// Optimization
optimization: {
minimize: isProduction,
// Disable module concatenation in dev mode to avoid cross-chunk dependency issues
// Enable in production for better tree-shaking
concatenateModules: isProduction,
moduleIds: 'deterministic',
chunkIds: 'deterministic',
minimizer: isProduction
? [
new TerserPlugin({
parallel: true,
extractComments: false,
terserOptions: {
// Preserve Error subclass names in production so that the
// renderer's error-mapping layer (which keys off
// `err.name` / `err.constructor.name`) can still recognize
// classes like `QuotaExceededError`, `AbortError`, etc.
// after minification.
keep_classnames: /Error$|Exception$/,
keep_fnames: /Error$|Exception$/,
compress: {
pure_funcs: ['console.log', 'console.debug']
}
}
})
]
: [],
// Split both sync and async chunks so shared vendor code (React,
// Redux, framer-motion, @xyflow/react, etc.) isn't duplicated
// between the main renderer.js and every lazy phase chunk. With
// `chunks: 'async'` webpack only deduped inside async graphs, so
// React ended up copied into renderer.js, discoverPhase.chunk,
// organizePhase.chunk, and so on. Raising to `'all'` plus dedicated
// cacheGroups means the browser fetches a single react-vendor chunk
// once and reuses it across phases and the main entry — ~20%
// smaller total bytes and fewer inline duplicates in production.
splitChunks: {
chunks: 'all',
minSize: 20000,
minRemainingSize: 0,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
react: {
// Pin react + react-dom + scheduler together so HMR can swap
// the bundle atomically and we don't end up with two copies
// of React (which silently breaks hooks).
test: /[\\/]node_modules[\\/](react|react-dom|scheduler|use-sync-external-store)[\\/]/,
name: 'react-vendor',
priority: 40,
reuseExistingChunk: true
},
redux: {
test: /[\\/]node_modules[\\/](@reduxjs|react-redux|redux|immer|reselect)[\\/]/,
name: 'redux-vendor',
priority: 30,
reuseExistingChunk: true
},
framerMotion: {
// framer-motion is large (~60 KB gz) and only needed after
// first paint. Keep it in its own chunk so lazy-loading
// PhaseRenderer actually defers the parse cost.
test: /[\\/]node_modules[\\/](framer-motion|motion-utils|motion-dom)[\\/]/,
name: 'motion-vendor',
priority: 25,
reuseExistingChunk: true
},
flow: {
// @xyflow/react is only loaded by search canvas phases.
test: /[\\/]node_modules[\\/]@xyflow[\\/]/,
name: 'flow-vendor',
priority: 20,
reuseExistingChunk: true
},
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
};