forked from digitalfabrik/integreat-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebpack.config.ts
351 lines (326 loc) · 10.7 KB
/
webpack.config.ts
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
import ReactRefreshPlugin from '@pmmmwh/react-refresh-webpack-plugin'
import AssetsPlugin from 'assets-webpack-plugin'
import { CleanWebpackPlugin } from 'clean-webpack-plugin'
import CopyPlugin from 'copy-webpack-plugin'
import { readFileSync } from 'fs'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import { join, resolve } from 'path'
import ReactRefreshTypeScript from 'react-refresh-typescript'
import { Configuration, DefinePlugin, LoaderOptionsPlugin, optimize, WebpackPluginInstance } from 'webpack'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
import 'webpack-dev-server'
import loadBuildConfig, { WEB } from 'build-configs'
import { WebBuildConfigType } from 'build-configs/BuildConfigType'
// reset the tsconfig to the default configuration
delete process.env.TS_NODE_PROJECT
const SHORT_COMMIT_SHA_LENGTH = 8
// A first performance budget, which should be improved in the future: Maximum bundle size in Bytes; 2^20 = 1 MiB
// eslint-disable-next-line no-magic-numbers
const MiB = 2 ** 20
// eslint-disable-next-line no-magic-numbers
const MAX_BUNDLE_SIZE = 1.64 * MiB
// eslint-disable-next-line no-magic-numbers
const MAX_ASSET_SIZE = 2.1 * MiB
const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'))
const readVersionName = () => {
const versionFile = readJson(resolve(__dirname, '../../version.json'))
return versionFile.versionName
}
// https://developer.android.com/training/app-links/verify-site-associations#manual-verification
const generateAssetLinks = (buildConfig: WebBuildConfigType) => {
if (!buildConfig.apps) {
throw Error('Cannot generate asset links if no apps are available!')
}
return JSON.stringify(
[
{
relation: ['delegate_permission/common.handle_all_urls'],
target: {
namespace: 'android_app',
package_name: buildConfig.apps.android.applicationId,
sha256_cert_fingerprints: [buildConfig.apps.android.sha256CertFingerprint],
},
},
...buildConfig.allowedLookalikes.map(lookalikeSite => ({
relation: ['lookalikes/allowlist'],
target: { namespace: 'web', site: lookalikeSite },
})),
],
null,
2,
)
}
const generateAppleAppSiteAssociation = (buildConfig: WebBuildConfigType) => {
if (!buildConfig.apps) {
throw Error('Cannot generate apple app site association if no apps are available!')
}
return JSON.stringify(
{
applinks: {
apps: [],
details: [
{
appIDs: buildConfig.apps.ios.appleAppSiteAssociationAppIds,
paths: ['*', '/'],
},
],
},
},
null,
2,
)
}
const generateManifest = (content: Buffer, buildConfig: WebBuildConfigType) => {
const manifest = JSON.parse(content.toString())
manifest.version = readVersionName()
manifest.homepage_url = buildConfig.aboutUrls.default
manifest.theme_color = buildConfig.lightTheme.colors.themeColor
manifest.name = buildConfig.appName
manifest.description = buildConfig.appDescription
if (buildConfig.apps) {
manifest.related_applications = [
{
platform: 'play',
id: buildConfig.apps.android.applicationId,
url: `https://play.google.com/store/apps/details?id=${buildConfig.apps.android.applicationId}`,
},
{
platform: 'itunes',
url: `https://apps.apple.com/de/app/${buildConfig.apps.ios.appStoreName}/id${buildConfig.apps.ios.appStoreId}`,
},
]
}
manifest.short_name = manifest.name
return JSON.stringify(manifest, null, 2)
}
const createConfig = (
env: {
config_name?: string
dev_server?: boolean
bundle_analyzer?: boolean
version_name?: string
commit_sha?: string
} = {},
): Configuration => {
const {
config_name: buildConfigName,
commit_sha: passedCommitSha,
version_name: passedVersionName,
dev_server: devServer,
bundle_analyzer: bundleAnalyer,
} = env
if (!buildConfigName) {
throw new Error('Please specify a build config name')
}
const buildConfig = loadBuildConfig(buildConfigName, WEB)
const NODE_ENV = devServer ? '"development"' : '"production"'
process.env.NODE_ENV = NODE_ENV
// If version_name is not supplied read it from version file
const versionName = passedVersionName || readVersionName()
const shortCommitSha = passedCommitSha?.substring(0, SHORT_COMMIT_SHA_LENGTH) || 'Commit SHA unknown'
console.log('Used config: ', buildConfigName)
console.log('Version name: ', versionName)
console.log('Commit SHA: ', shortCommitSha)
if (devServer) {
console.log('Configured for running in dev server')
}
const configAssets = resolve(__dirname, `../node_modules/build-configs/${buildConfigName}/assets`)
const nodeModules = resolve(__dirname, '../node_modules')
const rootNodeModules = resolve(__dirname, '../../node_modules')
const wwwDirectory = resolve(__dirname, '../www')
const distDirectory = resolve(__dirname, `../dist/${buildConfigName}`)
const srcDirectory = resolve(__dirname, '../src')
const wellKnownDirectory = resolve(distDirectory, '.well-known')
const bundleReportDirectory = resolve(__dirname, '../reports/bundle')
const manifestPreset = resolve(__dirname, 'manifest.json')
const assetLinksPreset = resolve(__dirname, 'assetlinks.json')
const appleAppSiteAssociationPreset = resolve(__dirname, 'apple-app-site-association')
const plugins: WebpackPluginInstance[] = []
if (devServer) {
plugins.push(new ReactRefreshPlugin())
}
const config: Configuration = {
mode: devServer ? 'development' : 'production',
resolve: {
extensions: ['.tsx', '.ts', '.js'],
modules: [nodeModules, rootNodeModules],
alias: {
'mapbox-gl': 'maplibre-gl',
},
},
// The base directory for resolving the entry option
context: srcDirectory,
// The entry point for the bundle
entry: [
'!!style-loader!css-loader!normalize.css/normalize.css',
/* The main entry point of your JavaScript application */
'./index.tsx',
],
// Options affecting the output of the compilation
output: {
path: distDirectory,
publicPath: '/',
filename: devServer ? '[name].js?[contenthash]' : '[name].[contenthash].js',
chunkFilename: devServer ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
sourcePrefix: ' ',
},
optimization: {
usedExports: true,
runtimeChunk: 'single',
},
devtool: 'source-map',
devServer: {
static: { directory: distDirectory },
compress: true,
port: 9000,
host: '0.0.0.0', // This enables devices in the same network to connect to the dev server
hot: true,
historyApiFallback: true,
},
// What information should be printed to the console
stats: 'minimal',
performance: {
hints: !devServer ? 'error' : false,
maxEntrypointSize: MAX_BUNDLE_SIZE,
maxAssetSize: MAX_ASSET_SIZE,
},
// The list of plugins for Webpack compiler
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: !bundleAnalyer ? 'disabled' : 'static',
generateStatsFile: !devServer,
openAnalyzer: false,
reportFilename: join(bundleReportDirectory, 'report.html'),
statsFilename: join(bundleReportDirectory, 'stats.json'),
}),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: buildConfig.appName,
template: 'index.ejs',
templateParameters: {
config: buildConfig,
},
}),
new CopyPlugin({
patterns: [
{ from: wwwDirectory, to: distDirectory },
{ from: configAssets, to: distDirectory },
{
from: manifestPreset,
to: distDirectory,
transform: (content: Buffer) => generateManifest(content, buildConfig),
},
...(buildConfig.apps
? [
{
from: assetLinksPreset,
to: wellKnownDirectory,
transform: () => generateAssetLinks(buildConfig),
},
{
from: appleAppSiteAssociationPreset,
to: distDirectory,
transform: () => generateAppleAppSiteAssociation(buildConfig),
},
]
: []),
],
}),
new DefinePlugin({
'process.env.NODE_ENV': NODE_ENV,
__VERSION_NAME__: JSON.stringify(versionName),
__COMMIT_SHA__: JSON.stringify(shortCommitSha),
__BUILD_CONFIG_NAME__: JSON.stringify(buildConfigName),
__BUILD_CONFIG__: JSON.stringify(buildConfig),
}),
// Emit a JSON file with assets paths
// https://github.com/sporto/assets-webpack-plugin#options
new AssetsPlugin({
path: distDirectory,
filename: 'assets.json',
prettyPrint: true,
}),
new LoaderOptionsPlugin({
debug: devServer,
minimize: !devServer,
}),
...plugins,
],
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
...(devServer && {
getCustomTransformers: () => ({
before: [ReactRefreshTypeScript()],
}),
}),
},
},
],
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
type: 'javascript/auto',
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
},
},
{
loader: 'img-loader',
options: {
enabled: !devServer,
gifsicle: {
interlaced: false,
},
mozjpeg: {
progressive: true,
arithmetic: false,
},
optipng: false,
pngquant: {
floyd: 0.5,
speed: 2,
},
svgo: {
plugins: [{ removeTitle: true }, { convertPathData: false }],
},
},
},
],
},
{
test: /\.(eot|ttf|wav|mp3)$/,
type: 'assets/resource',
},
],
},
}
if (!devServer) {
config.plugins?.push(new optimize.AggressiveMergingPlugin())
}
return config
}
export default createConfig