This repository has been archived by the owner on Sep 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webpack.config.js
529 lines (484 loc) · 15.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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Webpack
const webpack = require('webpack');
// Webpack plugins
const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const dotenv = require('dotenv');
// Node helpers
const path = require('path');
const execSync = require('child_process').execSync;
const fs = require('fs');
// Constants
const entryPath = path.join(__dirname, 'src/static/index.js');
const outputPath = path.join(__dirname, 'dist');
const orgPaths = path.join(__dirname, 'orgs');
const validOrgIds = fs
.readdirSync(orgPaths)
.map((file) => path.basename(file, '.json'));
// Webpack setup
// -------------
//
// Quick usage:
//
// - development: run "yarn start"
// - production: run "yarn build"
//
// More details:
//
// To do development, run "yarn start". This will serve the code
// locally at the designated port. All Elm, JavaScript, and Sass
// files will be hot reloaded into the browser. The standard URL
// for the development server is http://localhost:8000/.
//
// For production, run "yarn build". This will create files that
// can be served by any static file web server. While it's important
// to not cache index.html, all files in the static directory (CSS,
// images, fonts, and other resources) can be cached as they have
// hashed filenames. For best results, it's recommended to put these
// files on a CDN.
//
// Options:
//
// --baseUrl=<url> Set the base URL for service calls, etc.
// --production Set the target environment to production.
// --development Set the target environment to development.
// --languageSwitcher Set if the languageSwitcher will be shown.
// --debug Set the target environment to production with
// --the Elm debugger enabled.
//
// How to use options:
//
// <yarn command> -- <options>
// <webpack command> <options>
//
// Examples:
//
// yarn start -- --baseUrl=<url>
// yarn build -- --debug
//
// webpack --debug
// webpack serve --hot --inline --baseUrl=<url>
// -- Helpers
const production = 'env-production';
const development = 'env-development';
const debug = 'env-debug';
// Try to load .env file in root directory.
function loadDotenv() {
const dotenvPath = path.join(__dirname, '.env');
if (!fs.existsSync(dotenvPath)) {
return;
}
const result = dotenv.config({
path: dotenvPath
});
if (result.error) {
console.error('.env file is invalid: ', result.error);
throw new Error('.env file is invalid');
}
console.log('Loaded .env file');
}
// Try to load local config file, otherwise use default config.
function loadConfig() {
const localConfigPath = path.join(__dirname, 'webpack.local.config.js');
if (fs.existsSync(localConfigPath)) {
try {
const localConfig = require(localConfigPath);
console.log('Loaded local config.');
return localConfig;
} catch (ex) {
console.error('Local config is invalid');
if (ex) {
throw ex;
} else {
throw new Error('Local config is invalid');
}
}
} else {
console.log('Local config not found, using default config.');
}
return {
host: '0.0.0.0',
port: 8000
};
}
// Get option from command line.
function getOption(optName, needsArgument, fallback) {
const args = process.argv;
if (needsArgument === true) {
const fullOptName = '--' + optName + '=';
for (let i = 0; i < process.argv.length; ++i) {
if (args[i].substr(0, fullOptName.length) === fullOptName) {
return args[i].substr(fullOptName.length);
}
}
return fallback;
} else {
return args.indexOf('--' + optName) !== -1;
}
}
// Get the target environment.
function getTargetEnv() {
if (getOption('production')) {
return production;
} else if (getOption('development')) {
return development;
} else if (getOption('debug')) {
return debug;
} else if (process.env.npm_lifecycle_event === 'build') {
return production;
}
return development;
}
// Get base URL from command line or config file.
function getBaseUrl(config, name) {
const wantedBaseUrl = getOption(name, true, null);
if (typeof wantedBaseUrl === 'string') {
return wantedBaseUrl;
}
if (typeof config[name] === 'string') {
return config[name];
}
if (typeof config[name] === 'object') {
if (isProduction || isDebug) {
if (
typeof config[name].production === 'string' &&
config[name].production.length > 0
) {
return config[name].production;
}
} else if (isDevelopment) {
if (
typeof config[name].development === 'string' &&
config[name].development.length > 0
) {
return config[name].development;
}
}
}
// Use root of current server as default backend. This won't work for
// development as the dev server only serves frontend code. It's just
// a semi-sane default.
return process.env.WEBSHOP_BASE_URL || '/';
}
function getFirebaseConfig(config) {
if (typeof config['firebaseConfig'] === 'object') {
return config['firebaseConfig'];
}
if (typeof process.env.WEBSHOP_FIREBASE_CONFIG === 'string') {
const config = JSON.parse(process.env.WEBSHOP_FIREBASE_CONFIG.trim());
return config;
}
throw Error(
'Need to set firebaseConfig in webpack.local.config.js or WEBSHOP_FIREBASE_CONFIG environment variable.'
);
}
function getOrgIdConfig(config) {
const orgId = process.env.WEBSHOP_ORG_ID || config.orgId;
const validOrgIdStrings = validOrgIds.join(', ');
if (!validOrgIds.includes(orgId)) {
throw Error(
`Missing valid "orgId". Valid org ids: ${validOrgIdStrings}`
);
}
return orgId;
}
// Get languageSwitcher from command line or config file
function getLanguageSwitcher(config) {
return getOption(
'languageSwitcher',
true,
config.languageSwitcher || false
);
}
// Try to run a Git command. If Git isn't found in the PATH, then we
// silently return an empty string.
function runGitCommand(command) {
try {
return ('' + execSync(['git', command].join(' '))).replace(
/[\s\r\n]+$/,
''
);
} catch (ex) {
return '';
}
}
// Run "git describe".
function gitDescribe() {
return runGitCommand('describe --always --tags');
}
// Return the current commit hash.
function gitCommitHash() {
return runGitCommand('rev-parse HEAD');
}
// -- Webpack setup
console.log('Initializing...');
// Load .env
loadDotenv();
// Local config
const localConfig = loadConfig();
const publicPath =
localConfig.publicPath || `${localConfig.host}:${localConfig.port}`;
// Determine build environment.
const TARGET_ENV = getTargetEnv();
const isProduction = TARGET_ENV === production || TARGET_ENV === debug;
const isDevelopment = TARGET_ENV === development;
const languageSwitcher = getLanguageSwitcher(localConfig);
const enableDebug = TARGET_ENV === development || TARGET_ENV === debug;
const orgId = getOrgIdConfig(localConfig);
const appConfig = require(`./orgs/${orgId}.json`);
// Common Webpack config. Everything here will be used in both the
// development and production environments.
const outputFilename = isDevelopment ? '[name].js' : '[chunkhash].js';
const commonConfig = {
mode: isDevelopment ? 'development' : 'production',
output: {
path: outputPath,
filename: `static/js/${outputFilename}`,
crossOriginLoading: 'anonymous',
publicPath: '/',
hashFunction: 'xxhash64',
hashDigestLength: 64
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
extensions: ['.js', '.elm', '.scss'],
alias: {
'@atb/theme/theme.css': `@atb-as/theme/lib/themes/${orgId}-theme/theme.css`,
'@atb/theme/typography.css': '@atb-as/theme/lib/typography.css'
}
},
module: {
noParse: /\.elm$/
},
target: 'web',
performance: {},
optimization: {
splitChunks: {
name: 'vendor',
minChunks: 2
},
emitOnErrors: false
},
plugins: [
new SubresourceIntegrityPlugin(),
new HtmlWebpackPlugin({
template: 'src/static/index.html',
inject: true,
filename: 'index.html',
minify: isDevelopment
? {}
: {
removeAttributeQuotes: false,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
removeComments: true,
removeEmptyAttributes: true
}
}),
new CopyPlugin({
patterns: [
{
from: 'src/static/manifest.json',
to: 'manifest.json',
transform(content, path) {
return JSON.stringify(
JSON.parse(content.toString('utf8'))
);
}
},
{
from: `src/static/assets/colors/favicon.ico`,
to: 'favicon.ico'
},
{
from: `src/static/assets/`,
to: 'assets/'
}
]
}),
new webpack.DefinePlugin({
elmFlags: JSON.stringify({
isDevelopment: isDevelopment,
baseUrl: getBaseUrl(localConfig, 'baseUrl'),
languageSwitcher: languageSwitcher || isDevelopment,
version: gitDescribe(),
commit: gitCommitHash(),
orgConf: appConfig,
intercomEnabled: !!(
process.env.INTERCOM_ENABLED || localConfig.intercomEnabled
)
}),
gaTrackingId: JSON.stringify(
process.env.GA_TRACKING_ID || localConfig.gaTrackingId
),
firebaseConfig: JSON.stringify(getFirebaseConfig(localConfig))
})
]
};
// Finally, export the Webpack configuration.
if (isDevelopment) {
console.log('Building for development...');
console.log('Serving locally...');
module.exports = merge(commonConfig, {
entry: [`webpack-dev-server/client?http://${publicPath}`, entryPath],
devServer: {
host: localConfig.host,
port: localConfig.port,
https: false,
allowedHosts: 'all',
historyApiFallback: true,
static: {
directory: path.join(__dirname, 'src')
},
proxy: localConfig.proxy || {
'/test/*': {
target: 'http://localhost:10000',
secure: false
}
}
},
module: {
rules: [
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
use: [
{
loader: 'elm-hot-webpack-loader'
},
{
loader: 'elm-webpack-loader',
options: {
verbose: true,
debug: true
}
}
]
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(eot|otf|ttf|woff|woff2)$/,
use: 'file-loader'
}
]
}
});
} else if (isProduction) {
console.log('Building for production...');
module.exports = merge(commonConfig, {
entry: entryPath,
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
use: {
loader: 'elm-webpack-loader',
options: {
debug: enableDebug,
optimize: !enableDebug
}
}
},
{
test: /\.(eot|otf|ttf|woff|woff2)$/i,
use: {
loader: 'file-loader',
options: {
name: 'static/res/[sha256:hash:base64].[ext]'
}
}
},
{
test: /\.(css|scss)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../../'
}
},
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
// Extract CSS into a separate file.
new MiniCssExtractPlugin({
filename: 'static/styles/[contenthash].css'
})
],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: 5,
compress: {
pure_funcs: [
'F2',
'F3',
'F4',
'F5',
'F6',
'F7',
'F8',
'F9',
'A2',
'A3',
'A4',
'A5',
'A6',
'A7',
'A8',
'A9'
],
pure_getters: true,
keep_fargs: false,
unsafe_comps: true,
unsafe: true,
passes: 3
}
}
}),
new CssMinimizerPlugin()
]
}
});
} else {
console.log('ERROR: Invalid target environment "' + TARGET_ENV + '".');
module.exports = {};
}