forked from openmrs/openmrs-esm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrspack.config.js
More file actions
487 lines (460 loc) · 16.2 KB
/
rspack.config.js
File metadata and controls
487 lines (460 loc) · 16.2 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
const {
CssExtractRspackPlugin,
CopyRspackPlugin,
DefinePlugin,
container,
util: { createHash },
} = require('@rspack/core');
const CleanWebpackPlugin = require('clean-webpack-plugin').CleanWebpackPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const WebpackPwaManifest = require('webpack-pwa-manifest');
const { basename, dirname, resolve } = require('path');
const { mkdirSync, readdirSync, statSync, readFileSync, writeFileSync } = require('node:fs');
const sass = require('sass-embedded');
const semver = require('semver');
const { removeTrailingSlash, getTimestamp } = require('./tools/helpers');
const { name, version, dependencies } = require('./package.json');
const sharedDependencies = require('./dependencies.json');
const frameworkVersion = require('@openmrs/esm-framework/package.json').version;
const timestamp = getTimestamp();
const production = 'production';
const allowedSuffixes = ['-app', '-widgets'];
const { ModuleFederationPlugin } = container;
const openmrsAddCookie = process.env.OMRS_ADD_COOKIE;
const openmrsApiUrl = removeTrailingSlash(process.env.OMRS_API_URL || '/openmrs');
const openmrsPublicPath = removeTrailingSlash(process.env.OMRS_PUBLIC_PATH || '/openmrs/spa');
const openmrsProxyTarget = process.env.OMRS_PROXY_TARGET || 'https://dev3.openmrs.org/';
const openmrsPageTitle = process.env.OMRS_PAGE_TITLE || 'OpenMRS';
const openmrsFavicon = process.env.OMRS_FAVICON || `${openmrsPublicPath}/favicon.ico`;
const openmrsEnvironment = process.env.OMRS_ENV || process.env.NODE_ENV || '';
const openmrsOffline = process.env.OMRS_OFFLINE === 'enable';
const openmrsDefaultLocale = process.env.OMRS_ESM_DEFAULT_LOCALE || 'en';
const openmrsImportmapDef = process.env.OMRS_ESM_IMPORTMAP;
const openmrsImportmapUrl = process.env.OMRS_ESM_IMPORTMAP_URL || `${openmrsPublicPath}/importmap.json`;
const openmrsRoutesDef = process.env.OMRS_ROUTES;
const openmrsRoutesUrl = process.env.OMRS_ROUTES_URL || `${openmrsPublicPath}/routes.registry.json`;
const openmrsCoreApps = process.env.OMRS_ESM_CORE_APPS_DIR || resolve(__dirname, '../../apps');
const openmrsConfigUrls = (process.env.OMRS_CONFIG_URLS || '')
.split(';')
.filter((url) => url.length > 0)
.map((url) => JSON.stringify(url))
.join(', ');
const openmrsJsCssAssets = (process.env.OMRS_JS_CSS_ASSETS || '').split(';').filter((filePath) => filePath.length > 0);
const openmrsCleanBeforeBuild =
(() => {
try {
return (
process.env.OMRS_CLEAN_BEFORE_BUILD === undefined ||
(typeof process.env.OMRS_CLEAN_BEFORE_BUILD === 'boolean' && process.env.OMRS_CLEAN_BEFORE_BUILD) ||
(typeof process.env.OMRS_CLEAN_BEFORE_BUILD === 'string' &&
process.env.OMRS_CLEAN_BEFORE_BUILD.toLowerCase() !== 'false')
);
} catch {
// this is intensionally a no-op
}
return undefined;
})() ?? true;
function checkDirectoryExists(dirName) {
if (dirName) {
try {
return statSync(dirName).isDirectory();
} catch {
return false;
}
}
return false;
}
function checkFileExists(filename) {
if (filename) {
try {
return statSync(filename).isFile();
} catch {
return false;
}
}
return false;
}
function checkDirectoryHasContents(dirName) {
if (checkDirectoryExists(dirName)) {
const contents = readdirSync(dirName);
return contents.length > 0;
} else {
return false;
}
}
// taken from: https://stackoverflow.com/a/6969486
// this function is CC BY-SA 4.0
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* @param {Record<string, string>} env
* @param {Array<string>} argv
* @returns {import("@rspack/core").Configuration}
*/
module.exports = (env, argv = []) => {
const mode = argv.mode || process.env.NODE_ENV || production;
const outDir = mode === production ? 'dist' : 'lib';
const isProd = mode === 'production';
const appPatterns = [];
const coreImportmap = {
imports: {},
};
const coreRoutes = {};
if (!isProd && checkDirectoryExists(openmrsCoreApps)) {
readdirSync(openmrsCoreApps).forEach((dir) => {
const appDir = resolve(openmrsCoreApps, dir);
if (checkDirectoryExists(appDir)) {
const { name, browser } = require(resolve(appDir, 'package.json'));
const distDir = resolve(appDir, dirname(browser));
if (allowedSuffixes.some((suffix) => name.endsWith(suffix))) {
if (checkDirectoryHasContents(distDir)) {
appPatterns.push({
from: distDir,
to: dir,
});
coreImportmap.imports[name] = `./${dir}/${basename(browser)}`;
const routesFile = resolve(distDir, 'routes.json');
if (checkFileExists(routesFile)) {
coreRoutes[name] = JSON.parse(readFileSync(routesFile));
}
} else {
console.warn(`Not serving ${name} because couldn't find ${distDir}`);
}
}
}
});
}
const assetsPatterns = openmrsJsCssAssets.map((asset) => ({ from: asset, to: 'assets' }));
// Compile the styleguide SCSS to CSS outside of rspack so it's a pure static file
// with no JS involvement. The result is content-hashed for long-term caching.
// Sass preserves @import of .css files as plain CSS @import rules rather than
// inlining them, so we strip those out and prepend the actual file contents.
const sassOutput = sass.compile(require.resolve('@openmrs/esm-styleguide/styles'), {
style: isProd ? 'compressed' : 'expanded',
quietDeps: true,
loadPaths: [resolve(__dirname, '..', '..', '..', 'node_modules')],
}).css;
const cssImportRegex = /@import\s*["']([^"']+)["']\s*;?\n?/g;
const inlinedImports = [];
const nodeModulesDir = resolve(__dirname, '..', '..', '..', 'node_modules');
const strippedCSS = sassOutput.replace(cssImportRegex, (_, importPath) => {
const resolvedPath = resolve(nodeModulesDir, importPath);
if (checkFileExists(resolvedPath)) {
inlinedImports.push(readFileSync(resolvedPath, 'utf-8'));
} else {
console.warn(`Could not resolve CSS import: ${importPath}`);
return `@import "${importPath}";\n`;
}
return '';
});
// Rewrite url("~package/path") references to url("fonts/filename") and collect
// the actual font file paths so they can be copied to dist/fonts/.
const fontAssets = new Set();
const resolvedCSS = (inlinedImports.join('\n') + strippedCSS).replace(
/url\(["']?~([^"')]+)["']?\)/g,
(_, assetPath) => {
const resolvedPath = resolve(nodeModulesDir, assetPath);
if (checkFileExists(resolvedPath)) {
fontAssets.add(resolvedPath);
return `url("fonts/${basename(resolvedPath)}")`;
}
console.warn(`Could not resolve font asset: ${assetPath}`);
return `url("${assetPath}")`;
},
);
const styleguideCSS = resolvedCSS;
let openmrsCssFilename = 'openmrs.css';
if (isProd) {
const cssHash = createHash('sha256').update(styleguideCSS).digest('hex').slice(0, 16);
openmrsCssFilename = `openmrs.${cssHash}.css`;
}
const cssTmpDir = resolve(__dirname, '.tmp');
mkdirSync(cssTmpDir, { recursive: true });
writeFileSync(resolve(cssTmpDir, openmrsCssFilename), styleguideCSS);
const fontPatterns = [...fontAssets].map((fontPath) => ({ from: fontPath, to: 'fonts' }));
return {
entry: resolve(__dirname, 'src/index.ts'),
output: {
filename: isProd ? 'openmrs.[contenthash].js' : 'openmrs.js',
chunkFilename: '[chunkhash].js',
path: resolve(__dirname, outDir),
publicPath: '',
hashFunction: 'xxhash64',
},
target: 'web',
// Module Federation v1.5 is incompatible with lazy compilation
lazyCompilation: false,
devServer: {
compress: true,
open: [`${openmrsPublicPath}/`.substring(1)],
devMiddleware: {
publicPath: `${openmrsPublicPath}/`,
},
historyApiFallback: {
rewrites: [
{
from: new RegExp(`^${escapeRegExp(openmrsPublicPath)}/.*(?!\\.(?!html).+$)`),
to: `${openmrsPublicPath}/index.html`,
},
],
},
proxy: [
{
/**
* @param {String} path
*/
context(path) {
if (!path) {
return false;
}
if (path.startsWith(openmrsPublicPath)) {
if (basename(path).indexOf('.') >= 0) {
return true;
} else {
return false;
}
}
if (path.startsWith(openmrsApiUrl)) {
return true;
}
return false;
},
target: openmrsProxyTarget,
changeOrigin: true,
/**
* @param {Request} proxyReq
*/
onProxyReq(proxyReq) {
if (openmrsAddCookie) {
const origCookie = proxyReq.getHeader('cookie');
const newCookie = `${origCookie};${openmrsAddCookie}`;
proxyReq.setHeader('cookie', newCookie);
}
},
/**
* @param {Response} proxyRes
*/
onProxyRes(proxyRes) {
if (proxyRes.headers) {
delete proxyRes.headers['content-security-policy'];
}
},
/**
* @param {string} path
* @param {Request} req
* @returns {string}
*/
pathRewrite(path) {
if (path.startsWith(openmrsPublicPath)) {
const matcher = /^.*\/([^\/]*\.(?!html|js)[^.]+)$/i.exec(path);
if (matcher) {
return `${openmrsPublicPath}/${matcher[1]}`;
}
}
return path;
},
},
],
static: ['src/assets'],
},
watchOptions: {
ignored: ['.git', 'test-results'],
},
mode,
devtool: isProd ? 'hidden-nosources-source-map' : 'eval-source-map',
module: {
rules: [
{
test: /openmrs-esm-styleguide\.css$/,
use: [
isProd
? { loader: require.resolve(CssExtractRspackPlugin.loader) }
: { loader: require.resolve('style-loader') },
{ loader: require.resolve('css-loader') },
],
},
{
test: /\.css$/,
exclude: [/openmrs-esm-styleguide\.css$/],
use: [
isProd
? { loader: require.resolve(CssExtractRspackPlugin.loader) }
: { loader: require.resolve('style-loader') },
{ loader: require.resolve('css-loader') },
],
},
{
test: /\.s[ac]ss$/,
use: [
isProd
? { loader: require.resolve(CssExtractRspackPlugin.loader) }
: { loader: require.resolve('style-loader') },
{ loader: require.resolve('css-loader') },
{
loader: require.resolve('sass-loader'),
options: { sassOptions: { quietDeps: true } },
},
],
},
{
test: /\.(woff|woff2|png)?$/,
type: 'asset/resource',
},
{
test: /\.(svg|html)$/,
type: 'asset/source',
},
{
test: /\.(j|t)sx?$/,
use: [
{
loader: 'builtin:swc-loader',
},
],
},
],
},
optimization: {
splitChunks: {
maxAsyncRequests: Infinity,
maxInitialRequests: 1,
cacheGroups: {
default: {
minChunks: 1,
reuseExistingChunk: true,
},
},
},
},
resolve: {
mainFields: ['module', 'main'],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', '.scss'],
fallback: {
http: false,
stream: false,
https: false,
zlib: false,
url: false,
},
alias: {
'@openmrs/esm-framework': '@openmrs/esm-framework/src/internal',
'lodash.debounce': 'lodash-es/debounce',
'lodash.findlast': 'lodash-es/findLast',
'lodash.isequal': 'lodash-es/isEqual',
'lodash.omit': 'lodash-es/omit',
'lodash.throttle': 'lodash-es/throttle',
// ugly, stupid hack to support dynamic translation resolution here
'@openmrs/esm-translations/translations': resolve(
dirname(require.resolve('@openmrs/esm-translations/package.json')),
'translations',
),
},
},
plugins: [
openmrsCleanBeforeBuild && new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
inject: false,
scriptLoading: 'blocking',
publicPath: openmrsPublicPath,
template: resolve(__dirname, 'src/index.ejs'),
templateParameters: {
openmrsApiUrl,
openmrsPublicPath,
openmrsFavicon,
openmrsPageTitle,
openmrsDefaultLocale,
openmrsImportmapDef,
openmrsImportmapUrl,
openmrsRoutesDef,
openmrsRoutesUrl,
openmrsOffline,
openmrsEnvironment,
openmrsConfigUrls,
openmrsCoreImportmap: appPatterns.length > 0 && JSON.stringify(coreImportmap),
openmrsCoreRoutes: Object.keys(coreRoutes).length > 0 && JSON.stringify(coreRoutes),
openmrsCssFilename,
openmrsExtraAssets: openmrsJsCssAssets.map((fileName) => 'assets/' + basename(fileName)),
},
}),
new WebpackPwaManifest({
name: openmrsPageTitle,
short_name: openmrsPageTitle,
publicPath: openmrsPublicPath,
description: 'Open source Health IT by and for the entire planet, starting with the developing world.',
background_color: '#ffffff',
theme_color: '#005d5d',
icons: [
{
src: resolve(__dirname, 'src/assets/logo-512.png'),
sizes: [96, 128, 144, 192, 256, 384, 512],
},
],
}),
new CopyRspackPlugin({
patterns: [
{ from: resolve(__dirname, 'src/assets') },
{ from: resolve(cssTmpDir, openmrsCssFilename), to: openmrsCssFilename },
...fontPatterns,
...appPatterns,
...assetsPatterns,
],
}),
new ModuleFederationPlugin({
name,
shared: sharedDependencies.reduce((obj, depName) => {
// This just attempts to align the requiredVersion with what we usually have in peerDependencies
let version = dependencies[depName];
if (version) {
if (version.startsWith('^')) {
version = `${semver.parse(version.slice(1)).major}.x`;
} else if (version.startsWith('~')) {
const semVer = semver.parse(version.slice(1));
version = `${semVer.major}.${semVer.minor}.x`;
} else if (version === 'workspace:*') {
version = `${semver.parse(require(`${depName}/package.json`).version).major}.X`;
}
}
if (depName === 'swr') {
// SWR is annoying with Module Federation
// See: https://github.com/webpack/webpack/issues/16125 and https://github.com/vercel/swr/issues/2356
obj['swr/_internal'] = {
requiredVersion: version,
strictVersion: false,
singleton: true,
import: 'swr/_internal',
shareKey: 'swr/_internal',
shareScope: 'default',
version: require('swr/package.json').version,
};
} else {
obj[depName] = {
requiredVersion: version ?? false,
strictVersion: false,
singleton: true,
import: depName,
shareKey: depName,
shareScope: 'default',
};
}
return obj;
}, {}),
}),
isProd &&
new CssExtractRspackPlugin({
filename: '[contenthash].css',
ignoreOrder: true,
}),
new DefinePlugin({
'process.env.BUILD_VERSION': JSON.stringify(`${version}-${timestamp}`),
'process.env.FRAMEWORK_VERSION': JSON.stringify(frameworkVersion),
'process.env.NODE_ENV': JSON.stringify(mode),
}),
new BundleAnalyzerPlugin({
analyzerMode: env?.analyze ? 'static' : 'disabled',
}),
].filter(Boolean),
ignoreWarnings: [/.*InjectManifest has been called multiple times.*/],
};
};