-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathwebpack.config.js
More file actions
283 lines (276 loc) · 10.7 KB
/
webpack.config.js
File metadata and controls
283 lines (276 loc) · 10.7 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
/* jshint esversion: 6 */
const CopyPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SourceMapDevToolPlugin = require('webpack/lib/SourceMapDevToolPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const UnusedWebpackPlugin = require('unused-webpack-plugin');
const WebpackShellPluginNext = require('webpack-shell-plugin-next');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { execSync } = require('child_process');
const { DateTime } = require('luxon');
const port = process.env.PORT || 4000;
const isHTTPS = process.env.PROTOCOL && process.env.PROTOCOL === 'HTTPS';
const isWebApp = !process.env.npm_lifecycle_script.includes('CORDOVA=1');
const useRealCerts = process.env.npm_lifecycle_script.includes('USE_REAL_CERTS=1');
const host = process.env.HOSTNAME || (useRealCerts ? 'wevotedeveloper.com' : 'localhost');
// const isProduction = process.env.npm_lifecycle_script.includes('PRODUCTION=1');
const source = isWebApp ? 'src' : 'srcCordova';
const bundleAnalysis = process.env.ANALYSIS || false; // enable the interactive bundle analyser and the Unused component analyzer
const minimized = process.env.MINIMIZED === '1' || false; // enable the Terser plugin that strips comments and shrinks long variable names
const verBits = process.version.split('.');
const major = parseInt(verBits[0].replace('v', ''));
const sslKey = process.env.HTTPS_SSL_KEY || (useRealCerts ? `./${source}/cert/wevotedeveloper.com_key.txt` : `./${source}/cert/server.key`);
const sslCert = process.env.HTTPS_SSL_CERT || (useRealCerts ? `./${source}/cert/wevotedeveloper.com.crt` : `./${source}/cert/server.crt`);
if (major < 22) {
console.error(`The minimum Node version is: v22.0.0, but you are running ${process.version}\n`);
} else {
console.log(`Node version is: ${process.version}`);
}
const sslOptions = {};
if (useRealCerts) {
console.log('useRealCerts in webpack.config.js ', useRealCerts);
// Override SSL options for testing with Cordova and real authoritative certs
//sslOptions.requestCert = true;
//sslOptions.passphrase = 'webpack-dev-server';
}
// console.log('key: ', fs.readFileSync(sslKey).toString());
// console.log('cert: ', fs.readFileSync(sslCert).toString());
async function getStatusValues () {
const stats = {};
try {
stats.nodeVersion = execSync('node --version').toString().trim();
stats.npmVersion = execSync('npm --version').toString().trim();
} catch (error) {
console.log('ERROR in getGitValues node/npm: ', error);
}
try {
console.log('Working Directory: ', __dirname);
stats.NODISPLAY_dirname = __dirname;
const files = fs.readdirSync(__dirname);
console.log(JSON.stringify(files));
stats.NODISPLAY_root_dir_files = JSON.stringify(files);
// set default values
stats.Pull_request = 'none';
stats.Git_committed_date = 'none';
stats.Git_commit_hash = 'Not Found';
try {
let hash = fs.readFileSync('./git_commit_hash', 'utf8');
hash = hash.trim();
if (hash) {
stats.NODISPLAY_hash = hash;
console.log('Hash: ', hash);
const hashURL = `https://github.com/wevote/weconnect-client/commit/${hash}`;
console.log('hashURL: ', hashURL);
stats.NODISPLAY_hashURL = hashURL;
// Use the GitHub REST API instead of scraping HTML — works for all commit types
const apiHeaders = { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'weconnect-client-build' };
// Get commit details (date)
const commitResponse = await fetch(`https://api.github.com/repos/wevote/weconnect-client/commits/${hash}`, { headers: apiHeaders });
if (!commitResponse.ok) {
throw new Error(`GitHub API returned ${commitResponse.status} for commit ${hash}`);
}
const commitData = await commitResponse.json();
let committedDate;
try {
committedDate = commitData.commit.committer.date || commitData.commit.author.date;
} catch (error) {
committedDate = commitData.commit.author.date;
}
console.log('committedDate: ', committedDate);
const date = new DateTime(committedDate);
stats.Git_committed_date = date.toLocaleString(DateTime.DATETIME_MED_WITH_SECONDS);
stats.Git_commit_hash = `<a href="${hashURL}">${hash}</a>`;
// Get associated pull request number
const prsResponse = await fetch(`https://api.github.com/repos/wevote/weconnect-client/commits/${hash}/pulls`, { headers: apiHeaders });
if (prsResponse.ok) {
const prs = await prsResponse.json();
if (prs.length > 0) {
stats.Pull_request = `#${prs[0].number}`;
console.log('Pull_request: ', stats.Pull_request);
} else {
stats.Pull_request = 'none';
}
}
}
} catch (error) {
console.log('Error reading git_commit_hash file:', error);
}
} catch (error) {
console.log('Error in getStatusValues git: ', error);
stats.Pull_request = 'none';
stats.Git_committed_date = 'none';
stats.Git_commit_hash = 'none';
}
return stats;
}
module.exports = async (env, argv) => {
const stats = await getStatusValues();
console.log('getStatusValues', JSON.stringify(stats));
return {
entry: path.resolve(__dirname, `./${source}/index.jsx`),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules|srcDeprecated/,
use: ['babel-loader'],
},
{
test: /\.(png|jp(e*)g|svg|eot|woff|ttf)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/',
exclude: /srcDeprecated/,
name: '[path][name].[ext]',
},
},
],
},
],
},
optimization: {
minimize: minimized,
minimizer: [
...(minimized ? [
new TerserPlugin({
parallel: true,
terserOptions: {
// https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
format: {
comments: false,
},
},
}),
] : []),
new CssMinimizerPlugin({
test: /\.css$/i,
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
},
],
},
}),
],
},
resolve: {
modules: [path.resolve(__dirname, source), 'node_modules'],
extensions: ['*', '.js', '.jsx'],
alias: {
'@mui/styled-engine': '@mui/styled-engine-sc',
},
},
output: {
path: path.resolve(__dirname, './build'),
filename: isWebApp ? '[name].[contenthash].js' : 'bundle.js',
publicPath: isWebApp ? '/' : undefined,
},
// source-map is for OpenReplay
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin(),
new ESLintPlugin({ failOnError: false, failOnWarning: false }),
new HtmlWebpackPlugin({
title: 'WeConnect',
template: path.resolve(__dirname, `./${source}/index.html`),
}),
...(bundleAnalysis ? [
new UnusedWebpackPlugin({ // Set ANALYSIS to true to list (likely) unused files
directories: [path.join(__dirname, source)],
exclude: [
'/**/cert/',
'/**/global/svg-icons/',
'/*.test.js',
'/**/config*.*',
'extension.html',
'/sass/',
'/robots.txt',
'srcDeprecated',
],
root: __dirname,
}),
new BundleAnalyzerPlugin(),
] : []),
new CopyPlugin({
patterns: [
{ from: `${source}/robots.txt`, to: '.' },
{
from: `${source}/img`,
to: 'img/',
globOptions: { ignore: ['**/DO-NOT-BUNDLE/**']},
},
],
}),
new WebpackShellPluginNext({
onBuildEnd: {
scripts: ['node ./src/js/common/node/webPackPostBuild.js'],
blocking: false,
parallel: true,
},
}),
...(argv.mode === 'production' ? [
new webpack.DefinePlugin({
// We need to get webpack into production mode, to make it include the much smaller minimized libraries
// especially for React itself.
// PRODUCTION: JSON.stringify(true),
'process.env.NODE_ENV': JSON.stringify('production'),
WEBPACK_NODE_VERSION: JSON.stringify(stats.nodeVersion),
WEBPACK_NPM_VERSION: JSON.stringify(stats?.npmVersion || 'none'),
WEBPACK_PULL_REQUEST: JSON.stringify(stats?.Pull_request || 'none'),
WEBPACK_GIT_DATE: JSON.stringify(stats?.Git_committed_date || 'none'),
WEBPACK_GIT_HASH: JSON.stringify(stats?.Git_commit_hash || 'none'),
WEBPACK_NODISPLAY_DIRNAME: JSON.stringify(stats.NODISPLAY_dirname || 'none'),
WEBPACK_NODISPLAY_ROOT_DIR_FILES: JSON.stringify(stats.NODISPLAY_root_dir_files || 'none'),
}),
] : [
new webpack.DefinePlugin({
WEBPACK_NODE_VERSION: JSON.stringify(stats?.nodeVersion || 'none'),
WEBPACK_NPM_VERSION: JSON.stringify(stats?.npmVersion || 'none'),
WEBPACK_PULL_REQUEST: JSON.stringify(stats?.Pull_request || 'none'),
WEBPACK_GIT_DATE: JSON.stringify(stats?.Git_committed_date || 'none'),
WEBPACK_GIT_HASH: JSON.stringify(stats?.Git_commit_hash || 'none'),
WEBPACK_NODISPLAY_DIRNAME: JSON.stringify(stats.NODISPLAY_dirname || 'none'),
WEBPACK_NODISPLAY_ROOT_DIR_FILES: JSON.stringify(stats.NODISPLAY_root_dir_files || 'none'),
}),
new SourceMapDevToolPlugin({
filename: isWebApp ? null : '[file].map', // if no value is provided the sourcemap is inlined
exclude: [/node_modules/, /css/],
}),
]),
],
devServer: {
allowedHosts: ['wevotedeveloper.com', 'localhost'],
static: {
directory: path.join(__dirname, './build/index.html'),
},
host,
port,
historyApiFallback: true,
...(isHTTPS ? {
server: {
type: 'https',
options: {
...sslOptions,
key: fs.readFileSync(sslKey),
cert: fs.readFileSync(sslCert)
},
},
} : {}),
client: {
overlay: {
runtimeErrors: (error) => !error.message.includes('ResizeObserver loop'),
},
},
},
};
};