forked from openmrs/openmrs-esm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.js
271 lines (263 loc) · 8.45 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
const CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin;
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const WebpackPwaManifest = require("webpack-pwa-manifest");
const { InjectManifest } = require("workbox-webpack-plugin");
const { DefinePlugin, container } = require("webpack");
const { resolve, dirname, basename } = require("path");
const { readdirSync, statSync } = require("fs");
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 || "favicon.ico";
const openmrsOffline = process.env.OMRS_OFFLINE !== "disable";
const openmrsImportmapDef = process.env.OMRS_ESM_IMPORTMAP;
const openmrsCoreApps =
process.env.OMRS_ESM_CORE_APPS_DIR || resolve(__dirname, "../../apps");
const openmrsEnvironment = process.env.OMRS_ENV || process.env.NODE_ENV || "";
const openmrsImportmapUrl =
process.env.OMRS_ESM_IMPORTMAP_URL || `${openmrsPublicPath}/importmap.json`;
const openmrsConfigUrls = (process.env.OMRS_CONFIG_URLS || "")
.split(";")
.filter((url) => url.length > 0)
.map((url) => JSON.stringify(url))
.join(", ");
function checkDirectoryExists(dirName) {
if (dirName) {
try {
return statSync(dirName).isDirectory();
} catch {
return false;
}
}
return false;
}
function checkDirectoryHasContents(dirName) {
if (checkDirectoryExists(dirName)) {
const contents = readdirSync(dirName);
return contents.length > 0;
} else {
return false;
}
}
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: {},
};
if (checkDirectoryExists(openmrsCoreApps)) {
readdirSync(openmrsCoreApps).forEach((dir) => {
const appDir = resolve(openmrsCoreApps, dir);
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)}`;
console.info(`Serving built artifact for ${name} from ${distDir}`);
} else {
console.warn(`Not serving ${name} because couldn't find ${distDir}`);
}
}
});
}
return {
entry: resolve(__dirname, "src/index.ts"),
output: {
filename: "openmrs.js",
chunkFilename: "[chunkhash].js",
path: resolve(__dirname, outDir),
publicPath: "",
},
target: "web",
devServer: {
compress: true,
open: [`${openmrsPublicPath}/`.substring(1)],
devMiddleware: {
publicPath: `${openmrsPublicPath}/`,
},
historyApiFallback: {
rewrites: [
{
from: new RegExp(`^${openmrsPublicPath}/.*(?!\.(?!html?).+$)`),
to: `${openmrsPublicPath}/index.html`,
},
],
},
proxy: [
{
context: [`${openmrsApiUrl}/**`, `${openmrsPublicPath}/**`],
target: openmrsProxyTarget,
changeOrigin: true,
onProxyReq(proxyReq) {
if (openmrsAddCookie) {
const origCookie = proxyReq.getHeader("cookie");
const newCookie = `${origCookie};${openmrsAddCookie}`;
proxyReq.setHeader("cookie", newCookie);
}
},
},
],
},
mode,
devtool: isProd ? false : "inline-source-map",
module: {
rules: [
{
test: /\.s?css$/,
use: [
isProd
? { loader: require.resolve(MiniCssExtractPlugin.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: /\.jsx?$/,
use: [
{
loader: require.resolve("esbuild-loader"),
options: {
loader: "jsx",
},
},
],
},
{
test: /\.tsx?$/,
use: [
{
loader: require.resolve("esbuild-loader"),
options: {
loader: "tsx",
},
},
],
},
],
},
resolve: {
mainFields: ["module", "main"],
extensions: [".ts", ".tsx", ".js", ".jsx", ".css", ".scss"],
fallback: {
http: false,
stream: false,
https: false,
zlib: false,
url: false,
},
},
plugins: [
new CleanWebpackPlugin(),
new WebpackPwaManifest({
name: "OpenMRS",
short_name: "OpenMRS",
description:
"Open source Health IT by and for the entire planet, starting with the developing world.",
background_color: "#ffffff",
theme_color: "#000000",
icons: [
{
src: resolve(__dirname, "src/assets/logo-512.png"),
sizes: [96, 128, 144, 192, 256, 384, 512],
},
],
}),
new HtmlWebpackPlugin({
inject: false,
scriptLoading: "blocking",
publicPath: openmrsPublicPath,
template: resolve(__dirname, "src/index.ejs"),
templateParameters: {
openmrsApiUrl,
openmrsPublicPath,
openmrsFavicon,
openmrsPageTitle,
openmrsImportmapDef,
openmrsImportmapUrl,
openmrsOffline,
openmrsEnvironment,
openmrsConfigUrls,
openmrsCoreImportmap:
appPatterns.length > 0 && JSON.stringify(coreImportmap),
},
}),
new CopyWebpackPlugin({
patterns: [{ from: resolve(__dirname, "src/assets") }, ...appPatterns],
}),
new ModuleFederationPlugin({
name,
shared: sharedDependencies.reduce((obj, depName) => {
obj[depName] = {
requiredVersion: dependencies[depName] ?? false,
singleton: true,
eager: true,
import: depName,
shareKey: depName,
shareScope: "default",
};
return obj;
}, {}),
}),
isProd &&
new MiniCssExtractPlugin({
filename: "openmrs.css",
}),
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 && env.analyze ? "static" : "disabled",
}),
openmrsOffline &&
new InjectManifest({
swSrc: resolve(__dirname, "./src/service-worker/index.ts"),
swDest: "service-worker.js",
maximumFileSizeToCacheInBytes:
mode === production ? undefined : Number.MAX_SAFE_INTEGER,
additionalManifestEntries: [
{ url: openmrsImportmapUrl, revision: null },
],
}),
].filter(Boolean),
ignoreWarnings: [/.*InjectManifest has been called multiple times.*/],
};
};