-
Notifications
You must be signed in to change notification settings - Fork 411
/
base.js
389 lines (364 loc) · 11.8 KB
/
base.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
// This file is part of Indico.
// Copyright (C) 2002 - 2021 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import {createHash} from 'crypto';
import fs from 'fs';
import path from 'path';
import autoprefixer from 'autoprefixer';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import importOnce from 'node-sass-import-once';
import postcssURL from 'postcss-url';
import TerserPlugin from 'terser-webpack-plugin';
import webpack from 'webpack';
import {WebpackManifestPlugin} from 'webpack-manifest-plugin';
function _resolveTheme(rootPath, indicoClientPath, filePath) {
const indicoRelativePath = path.resolve(indicoClientPath, filePath);
if (
indicoClientPath &&
!fs.existsSync(path.resolve(rootPath, filePath)) &&
fs.existsSync(indicoRelativePath)
) {
return path.resolve(indicoClientPath, filePath);
}
return path.resolve(rootPath, filePath);
}
function _importOnce(...args) {
// Due to https://github.com/webpack-contrib/sass-loader/pull/958/files we need to
// use a different context for the importOnce plugin in order to keep the cache
// between calls to this function.
// Using a global one might work as well but like this it's scoped with the same
// lifetime which we had before the sass-loader update as `options` is cloned at
// the same time the object previously used in `this` was created (`context` in
// `getOptions`).
this.options._ctx = this.options._ctx || {options: this.options};
return importOnce.apply(this.options._ctx, args);
}
export function getThemeEntryPoints(config, prefix) {
const themes = config.themes;
const indicoClientPath = path.join(
config.isPlugin ? config.indico.build.clientPath : config.build.clientPath,
'styles'
);
const rootPath = path.join(config.build.rootPath);
return Object.assign(
...Object.keys(themes).map(k => {
const returnValue = {};
const escapedKey = k.replace('-', '_');
returnValue[`themes_${escapedKey}`] = [
_resolveTheme(rootPath, indicoClientPath, prefix + themes[k].stylesheet),
];
if (themes[k].print_stylesheet) {
returnValue[`themes_${escapedKey}.print`] = [
_resolveTheme(rootPath, indicoClientPath, prefix + themes[k].print_stylesheet),
];
}
return returnValue;
})
);
}
export function generateAssetPath(config, virtualVersion = false) {
// /css/whatever.css => /css/whatever__v123abcdef.css
return file => {
const relPath = path.relative(config.build.staticPath, file);
const {dir, name, ext} = path.parse(relPath);
const h = createHash('md5');
h.update(fs.readFileSync(file));
const hash = h.digest('hex').slice(0, 8);
// the "virtual version" is used for files that are loaded as-is from the
// static folder and thus do not actually get the hash in the physical
// file name. it is distinct from the normal version style so a rule on
// the web server can strip that version segment
const fileName = virtualVersion ? `${name}__v${hash}${ext}` : `${name}.${hash}${ext}`;
// .. -> _, like file-loader does
return dir.replace(/\.\./g, '_') + path.sep + fileName;
};
}
export function webpackDefaults(env, config, bundles, isPlugin = false) {
const globalBuildConfig = config.indico ? config.indico.build : config.build;
const currentEnv = (env ? env.NODE_ENV : null) || 'development';
const nodeModules = [
path.join(
config.build.indicoSourcePath || path.resolve(config.build.rootPath, '..'),
'node_modules'
),
];
if (config.isPlugin) {
// add plugin's node_modules in addition to the core's
nodeModules.push(path.resolve(config.build.rootPath, '../node_modules'));
}
const _cssLoaderOptions = {
url: true,
};
const scssIncludePath = path.join(
config.isPlugin
? path.resolve(config.build.indicoSourcePath, './indico/web/client')
: path.join(config.build.clientPath),
'styles'
);
function getDevtoolFilename(info) {
const root = path.resolve(globalBuildConfig.rootPath, '..');
return path.relative(root, info.absoluteResourcePath);
}
/**
* This function resolves SASS files using a [~][module:]path syntax
*/
function sassResolver(url) {
const match = url.match(/^(~?)(?:(\w+):)?([\w/-_]+)/);
if (match) {
const skipOverride = match[1] === '~';
const mod = match[2];
const file = match[3];
if (config.isPlugin) {
const {sassOverrides} = bundles;
if (skipOverride) {
if (!mod) {
return {file: path.join(config.indico.build.clientPath, 'styles', file)};
}
} else if (sassOverrides && sassOverrides[url]) {
return {file: path.join(config.build.clientPath, sassOverrides[url])};
}
}
if (!mod) {
return null;
}
const modPath = path.join(globalBuildConfig.rootPath, 'modules', mod);
return {file: path.join(modPath, 'client', file)};
}
return null;
}
/**
* This function resolves url(...)s in CSS files using a plugin:path syntax
*/
function postCSSURLResolver({url}) {
const m = url.match(/^(\w+):(.*)$/);
if (!m) {
return url;
}
const [name, relPath] = m.slice(1);
let prefix;
if (name === 'static') {
prefix = globalBuildConfig.staticURL;
} else {
prefix = path.join(globalBuildConfig.staticURL, 'static/plugins', name);
}
return path.join(prefix, relPath);
}
function buildSCSSLoader(cssLoaderOptions = {}) {
return [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: config.build.distURL,
},
},
{
loader: 'css-loader',
options: {
sourceMap: true,
url: !config.isPlugin,
...cssLoaderOptions,
},
},
{
loader: 'resolve-url-loader',
options: {
root: config.isPlugin ? false : config.build.staticPath,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
postcssOptions: {
plugins: [
autoprefixer,
postcssURL({
url: postCSSURLResolver,
}),
],
},
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
sassOptions: {
includePaths: [scssIncludePath],
outputStyle: 'compact',
importer: [sassResolver, _importOnce],
},
},
},
];
}
const indicoClientPath = globalBuildConfig.clientPath;
return {
devtool: 'source-map',
cache: true,
context: config.build.clientPath,
output: {
path: config.build.distPath,
filename: 'js/[name].[chunkhash:8].bundle.js',
publicPath: config.build.distURL,
devtoolModuleFilenameTemplate: info => `webpack:///${getDevtoolFilename(info)}`,
devtoolFallbackModuleFilenameTemplate: info =>
`webpack:///${getDevtoolFilename(info)}?${info.hash}`,
},
module: {
rules: [
{
test: /outdatedbrowser\/.+\.js$/,
loader: 'babel-loader',
options: {
// build JS targetting old browsers so they get the warning as well
presets: [['@babel/preset-env', {targets: {browsers: ['last 5 years', 'ie > 6']}}]],
},
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
oneOf: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: _cssLoaderOptions,
},
],
},
{
test: /\.module\.scss$/,
use: buildSCSSLoader({
modules: {
localIdentContext: path.resolve(globalBuildConfig.clientPath, '../../modules'),
localIdentName: '[path]___[name]__[local]___[contenthash:base64:5]',
},
importLoaders: 1,
}),
},
{
test: /\.scss$/,
use: buildSCSSLoader(),
},
],
},
],
},
plugins: [
new WebpackManifestPlugin({
fileName: 'manifest.json',
publicPath: config.build.distURL,
}),
// Do not load moment locales (we'll load them explicitly)
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash:8].css',
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
resolve: {
alias: [{name: 'indico', alias: path.join(indicoClientPath, 'js/')}],
// Webpack 5 does not include polyfills for node.js core modules by default
fallback: {path: require.resolve('path-browserify')},
symlinks: false,
extensions: ['.js', '.json', '.jsx'],
modules: nodeModules,
},
resolveLoader: {
modules: nodeModules,
},
externals: ({context, request}, callback) => {
// tell webpack to make certain packages use window.jQuery (and not load it again)
if (/^jquery$/.test(request) && /(selectize|fullcalendar)/.test(context)) {
return callback(null, 'jQuery');
}
return callback();
},
stats: {
assets: false,
children: false,
modules: false,
chunks: true,
chunkModules: false,
chunkOrigins: false,
chunksSort: 'name',
},
mode: currentEnv,
optimization: {
splitChunks: {
cacheGroups: isPlugin
? {}
: {
// 'common' chunk, which should include common dependencies
common: {
name: 'common',
chunks: chunk =>
chunk.canBeInitial() &&
// outdatedbrowser must be fully standalone since we can assume all other
// bundles to be broken in legacy browsers
chunk.name !== 'outdatedbrowser' &&
// having theme/print css in the common css bundle would break the interface
!/\.print$|^themes_/.test(chunk.name),
minChunks: 2,
},
// react/redux and friends since they are pretty big
react: {
test: /\/node_modules\/(react|redux|prop-types\/|lodash-es\/|fbjs\/)/,
name: 'react',
chunks: 'initial',
priority: 10,
},
semanticui: {
test: /node_modules\/(semantic-ui|indico-sui-theme)/,
name: 'semantic-ui',
chunks: 'initial',
priority: 10,
},
},
},
minimizer: [
new TerserPlugin({
exclude: [
// minification breaks angularjs :(
/js\/module_events\.registration\.[^.]+\.bundle\.js$/,
// "Unexpected token: punc (:) [js/mathjax/extensions/a11y/mathmaps/fr.js:2,25]"
/js\/mathjax(\/unpacked)?\/extensions\/a11y\/mathmaps\/.+\.js$/,
],
extractComments: false,
}),
],
},
};
}
export function indicoStaticLoader(config) {
return {
test: /\/static\/(images|fonts)\/.*\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/,
use: {
loader: 'file-loader',
options: {
name: generateAssetPath(config, true),
context: config.build.staticPath,
emitFile: false,
publicPath: config.build.staticURL,
},
},
};
}