This repository has been archived by the owner on Nov 22, 2023. It is now read-only.
forked from getsentry/sentry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.js
403 lines (376 loc) · 11.8 KB
/
webpack.config.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
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
/*eslint-env node*/
/*eslint import/no-nodejs-modules:0 */
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const babelConfig = require('./babel.config');
const ExtractTextPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const FixStyleOnlyEntriesPlugin = require('webpack-fix-style-only-entries');
const {env} = process;
const IS_PRODUCTION = env.NODE_ENV === 'production';
const IS_TEST = env.NODE_ENV === 'test' || env.TEST_SUITE;
const IS_STORYBOOK = env.STORYBOOK_BUILD === '1';
const WEBPACK_MODE = IS_PRODUCTION ? 'production' : 'development';
// HMR proxying
const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
const USE_HOT_MODULE_RELOAD =
!IS_PRODUCTION && SENTRY_BACKEND_PORT && SENTRY_WEBPACK_PROXY_PORT;
// this is set by setup.py sdist
const staticPrefix = path.join(__dirname, 'src/sentry/static/sentry');
const distPath = env.SENTRY_STATIC_DIST_PATH || path.join(staticPrefix, 'dist');
/**
* Locale file extraction build step
*/
if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
babelConfig.plugins.push([
'babel-gettext-extractor',
{
fileName: 'build/javascript.po',
baseDirectory: path.join(__dirname, 'src/sentry'),
functionNames: {
gettext: ['msgid'],
ngettext: ['msgid', 'msgid_plural', 'count'],
gettextComponentTemplate: ['msgid'],
t: ['msgid'],
tn: ['msgid', 'msgid_plural', 'count'],
tct: ['msgid'],
},
},
]);
}
/**
* Locale compilation and optimizations.
*
* Locales are code-split from the app and vendor chunk into separate chunks
* that will be loaded by layout.html depending on the users configured locale.
*
* Code splitting happens using the splitChunks plugin, configured under the
* `optimization` key of the webpack module. We create chunk (cache) groups for
* each of our supported locales and extract the PO files and moment.js locale
* files into each chunk.
*
* A plugin is used to remove the locale chunks from the app entry's chunk
* dependency list, so that our compiled bundle does not expect that *all*
* locale chunks must be loadd
*/
const localeCatalogPath = path.join(
__dirname,
'src',
'sentry',
'locale',
'catalogs.json'
);
const localeCatalog = JSON.parse(fs.readFileSync(localeCatalogPath, 'utf8'));
// Translates a locale name to a language code.
//
// * po files are kept in a directory represented by the locale name [0]
// * moment.js locales are stored as language code files
// * Sentry will request the user configured language from locale/{language}.js
//
// [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
const localeToLanguage = locale => locale.toLowerCase().replace('_', '-');
const supportedLocales = localeCatalog.supported_locales;
const supportedLanguages = supportedLocales.map(localeToLanguage);
// A mapping of chunk groups used for locale code splitting
const localeChunkGroups = {};
// No need to split the english locale out as it will be completely empty and
// is not included in the django layout.html.
supportedLocales.filter(l => l !== 'en').forEach(locale => {
const language = localeToLanguage(locale);
const group = `locale/${language}`;
// List of module path tests to group into locale chunks
const localeGroupTests = [
new RegExp(`locale\\/${locale}\\/.*\\.po$`),
new RegExp(`moment\\/locale\\/${language}\\.js$`),
];
// module test taken from [0] and modified to support testing against
// multiple expressions.
//
// [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
const groupTest = module =>
localeGroupTests.some(
pattern =>
module.nameForCondition && pattern.test(module.nameForCondition())
? true
: Array.from(module.chunksIterable).some(c => c.name && pattern.test(c.name))
);
localeChunkGroups[group] = {
name: group,
test: groupTest,
enforce: true,
};
});
/**
* Restirct translation files that are pulled in through app/translations.jsx
* and through moment/locale/* to only those which we create bundles for via
* locale/catalogs.json.
*/
const localeRestrictionPlugins = [
new webpack.ContextReplacementPlugin(
/sentry-locale$/,
path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
true,
new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
),
new webpack.ContextReplacementPlugin(
/moment\/locale/,
new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
),
];
/**
* When our locales are codesplit into cache groups, webpack expects that all
* chunks *must* be loaded before the main entrypoint can be executed. However,
* since we will only be using one locale at a time we do not want to load all
* locale chunks, just the one the user has enabled.
*
* This plugin removes the locale chunks from the app entrypoint's immediate
* chunk dependants list, ensuring the the compiled entrypoint will execute
* *without* all locale chunks loaded.
*/
const pluginName = 'OptionalLocaleChunkPlugin';
const clearLocaleChunks = chunks =>
chunks.filter(chunk => chunk.name !== 'app').forEach(chunk => {
const mainGroup = Array.from(chunk.groupsIterable)[0];
mainGroup.chunks = mainGroup.chunks.filter(
c => c.name && !c.name.startsWith('locale')
);
});
class OptionalLocaleChunkPlugin {
apply(compiler) {
compiler.hooks.compilation.tap(pluginName, compilation =>
compilation.hooks.afterOptimizeChunks.tap(pluginName, clearLocaleChunks)
);
}
}
/**
* Explicit codesplitting cache groups
*/
const cacheGroups = {
vendors: {
name: 'vendor',
test: /[\\/]node_modules[\\/]/,
priority: -10,
enforce: true,
chunks: 'initial',
},
...localeChunkGroups,
};
/**
* Main Webpack config for Sentry React SPA.
*/
const appConfig = {
mode: WEBPACK_MODE,
entry: {app: 'app'},
context: staticPrefix,
module: {
rules: [
{
test: /\.jsx?$/,
include: [staticPrefix],
exclude: /(vendor|node_modules|dist)/,
use: {
loader: 'babel-loader',
options: {...babelConfig, cacheDirectory: true},
},
},
{
test: /\.po$/,
use: {
loader: 'po-catalog-loader',
options: {
referenceExtensions: ['.js', '.jsx'],
domain: 'sentry',
},
},
},
{
test: /app\/icons\/.*\.svg$/,
use: ['svg-sprite-loader', 'svgo-loader'],
},
{
test: /\.css/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
exclude: /app\/icons\/.*\.svg$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
],
noParse: [
// don't parse known, pre-built javascript files (improves webpack perf)
/dist\/jquery\.js/,
/jed\/jed\.js/,
/marked\/lib\/marked\.js/,
],
},
plugins: [
/**
* Used to make our lodash modules even smaller
*/
new LodashModuleReplacementPlugin({
collections: true,
currying: true, // these are enabled to support lodash/fp/ features
flattening: true, // used by a dependency of react-mentions
shorthands: true,
}),
/**
* jQuery must be provided in the global scope specifically and only for
* bootstrap, as it will not import jQuery itself.
*
* We discourage the use of global jQuery through eslint rules
*/
new webpack.ProvidePlugin({jQuery: 'jquery'}),
/**
* Extract CSS into separate files.
*/
new ExtractTextPlugin(),
/**
* Defines environemnt specific flags.
*/
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(env.NODE_ENV),
IS_PERCY: JSON.stringify(env.CI && !!env.PERCY_TOKEN && !!env.TRAVIS),
},
}),
/**
* See above for locale chunks. These plugins help with that
* funcationality.
*/
new OptionalLocaleChunkPlugin(),
...localeRestrictionPlugins,
],
resolve: {
alias: {
app: path.join(staticPrefix, 'app'),
'app-test': path.join(__dirname, 'tests', 'js'),
'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
'integration-docs-platforms':
IS_TEST || IS_STORYBOOK
? path.join(__dirname, 'tests/fixtures/integration-docs/_platforms.json')
: path.join(__dirname, 'src/sentry/integration-docs/_platforms.json'),
},
modules: ['node_modules'],
extensions: ['.jsx', '.js', '.json'],
},
output: {
path: distPath,
filename: '[name].js',
sourceMapFilename: '[name].js.map',
},
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: 5,
maxAsyncRequests: 7,
cacheGroups,
},
},
devtool: IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map',
};
/**
* Legacy CSS Webpack appConfig for Django-powered views.
* This generates a single "sentry.css" file that imports ALL component styles
* for use on Django-powered pages.
*/
const legacyCssConfig = {
mode: WEBPACK_MODE,
entry: {
sentry: 'less/sentry.less',
// Below is for old plugins that use select2 when creating a new issue for a plugin
// e.g. Trello, Teamwork
select2: 'less/select2.less',
},
context: staticPrefix,
output: {
path: distPath,
},
plugins: [new FixStyleOnlyEntriesPlugin(), new ExtractTextPlugin()],
resolve: {
extensions: ['.less', '.js'],
modules: [staticPrefix, 'node_modules'],
},
module: {
rules: [
{
test: /\.less$/,
include: [staticPrefix],
use: [ExtractTextPlugin.loader, 'css-loader', 'less-loader'],
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
],
},
};
// Dev only! Hot module reloading
if (USE_HOT_MODULE_RELOAD) {
appConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
appConfig.devServer = {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
},
// Required for getsentry
disableHostCheck: true,
contentBase: './src/sentry/static/sentry',
hot: true,
// If below is false, will reload on errors
hotOnly: true,
port: SENTRY_WEBPACK_PROXY_PORT,
stats: 'errors-only',
overlay: true,
watchOptions: {
ignored: ['node_modules'],
},
publicPath: '/_webpack',
proxy: {
'!/_webpack': `http://localhost:${SENTRY_BACKEND_PORT}/`,
},
before: app =>
app.use((req, res, next) => {
req.url = req.url.replace(/^\/_static\/[^\/]+\/sentry\/dist/, '/_webpack');
next();
}),
};
}
const minificationPlugins = [
// This compression-webpack-plugin generates pre-compressed files
// ending in .gz, to be picked up and served by our internal static media
// server as well as nginx when paired with the gzip_static module.
new CompressionPlugin({
algorithm: 'gzip',
test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
}),
new OptimizeCssAssetsPlugin(),
// NOTE: In production mode webpack will automatically minify javascript
// using the TerserWebpackPlugin.
];
if (IS_PRODUCTION) {
// NOTE: can't do plugins.push(Array) because webpack/webpack#2217
minificationPlugins.forEach(function(plugin) {
appConfig.plugins.push(plugin);
legacyCssConfig.plugins.push(plugin);
});
}
module.exports = [appConfig, legacyCssConfig];