forked from ledgersmb/LedgerSMB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.js
426 lines (363 loc) · 13.2 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
/** @format */
/* eslint global-require:0, no-param-reassign:0, no-unused-vars:0 */
/* global getConfig */
const TARGET = process.env.npm_lifecycle_event;
if (TARGET !== 'readme') {
const fs = require("fs");
const glob = require("glob");
const path = require("path");
const webpack = require("webpack");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const CompressionPlugin = require("compression-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const DojoWebpackPlugin = require("dojo-webpack-plugin");
const { DuplicatesPlugin } = require("inspectpack/plugin");
const ESLintPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const StylelintPlugin = require("stylelint-bare-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const UnusedWebpackPlugin = require("unused-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // installed via npm
const argv = require("yargs").argv;
const prodMode =
process.env.NODE_ENV === "production" ||
argv.p ||
argv.mode === "production";
// Make sure all modules follow desired mode
process.env.NODE_ENV = prodMode ? "production" : "development";
const parallelJobs = process.env.CI ? 2 : true;
/* FUNCTIONS */
var includedRequires = [
"dijit/Dialog",
"dijit/form/Button",
"dijit/form/CheckBox",
"dijit/form/ComboBox",
"dijit/form/CurrencyTextBox",
"dijit/form/MultiSelect",
"dijit/form/NumberSpinner",
"dijit/form/NumberTextBox",
"dijit/form/RadioButton",
"dijit/form/Select",
"dijit/form/Textarea",
"dijit/form/TextBox",
"dijit/form/ToggleButton",
"dijit/form/ValidationTextBox",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/layout/TabContainer",
"dijit/Tooltip",
"lsmb/ToggleIncludeButton"
];
function findDataDojoTypes(fileName) {
var content = "" + fs.readFileSync(fileName);
// Return unique data-dojo-type refereces
return (
content.match(/(?<=['"]?data-dojo-type['"]?\s*=\s*")([^"]+)(?=")/gi) ||
[]
).filter((x, i, a) => a.indexOf(x) === i);
}
// Compute used data-dojo-type
glob.sync("**/*.html", {
ignore: ["lib/ui-header.html", "js/**", "js-src/{dojo,dijit,util}/**"],
cwd: "UI"
}).map(function (filename) {
const requires = findDataDojoTypes("UI/" + filename);
return includedRequires.push(...requires);
});
// Pull UI/js-src/lsmb
includedRequires = includedRequires
.concat(
glob
.sync("{js-src/lsmb/**/!(webpack.loaderConfig|main).js,src/*.js}", {
cwd: "UI"
})
.map(function (file) {
return file.replace(/\.js$/, "").replace(/js-src\//, "");
})
)
.filter((x, i, a) => a.indexOf(x) === i)
.sort();
/* LOADERS */
const javascript = {
test: /\.js$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"]
}
}
],
exclude: file => {
return /node_modules/.test(file) || /_scripts/.test(file);
}
};
const vue = {
test: /\.vue$/,
loader: "vue-loader"
};
const css = {
test: /\.css$/i,
use: [ MiniCssExtractPlugin.loader, "css-loader"]
};
const images = {
test: /\.(png|jpe?g|gif)$/i,
type: 'asset'
};
const html = {
test: /\.html$/,
use: [
{
loader: "ejs-loader",
options: {
esModule: false
}
}
]
};
const svg = {
test: /\.svg$/,
type: 'asset/resource'
};
/* PLUGINS */
const CleanWebpackPluginOptions = {
dry: false,
verbose: false
}; // delete all files in the js directory without deleting this folder
const ESLintPluginOptions = {
files: "**/*.js",
emitError: prodMode,
emitWarning: !prodMode
};
const StylelintPluginOptions = {
files: "**/*.css"
};
// Copy non-packed resources needed by the app to the release directory
const CopyWebpackPluginOptions = {
patterns: [
{ context: "../node_modules", from: "dijit/icons/**/*", to: "." },
{ context: "../node_modules", from: "dijit/nls/**/*", to: "." },
{ context: "../node_modules", from: "dojo/nls/**/*", to: "." },
{ context: "../node_modules", from: "dojo/resources/**/*", to: "." }
],
options: {
concurrency: 100
}
};
const DojoWebpackPluginOptions = {
loaderConfig: require("./UI/js-src/lsmb/webpack.loaderConfig.js"),
environment: { dojoRoot: "UI/js" }, // used at run time for non-packed resources (e.g. blank.gif)
buildEnvironment: { dojoRoot: "node_modules" }, // used at build time
locales: ["en"],
noConsole: true
};
// dojo/domReady (only works if the DOM is ready when invoked)
const NormalModuleReplacementPluginOptionsDomReady = function (data) {
const match = /^dojo\/domReady!(.*)$/.exec(data.request);
/* eslint-disable-next-line no-param-reassign */
data.request = "dojo/loaderProxy?loader=dojo/domReady!" + match[1];
};
const NormalModuleReplacementPluginOptionsSVG = function (data) {
var match = /^svg!(.*)$/.exec(data.request);
/* eslint-disable-next-line no-param-reassign */
data.request =
"dojo/loaderProxy?loader=svg&deps=dojo/text%21" +
match[1] +
"!" +
match[1];
};
const UnusedWebpackPluginOptions = {
// Source directories
directories: ["js-src/lsmb"],
// Exclude patterns
exclude: ["*.test.js"],
// Root directory (optional)
root: path.join(__dirname, "UI")
};
// Generate entries from file pattern
const mapFilenamesToEntries = (pattern) =>
glob.sync(pattern).reduce((entries, filename) => {
const [, name] = filename.match(/([^/]+)\.css$/);
return { ...entries, [name]: filename };
}, {});
const _dijitThemes = "+(claro|nihilo|soria|tundra)";
const lsmbCSS = {
...mapFilenamesToEntries(path.resolve("UI/css/*.css")),
...mapFilenamesToEntries(
path.resolve(
"node_modules/dijit/themes/" +
_dijitThemes +
"/" +
_dijitThemes +
".css"
)
)
};
var pluginsProd = [
// Clean UI/js before building (must be first)
new CleanWebpackPlugin(CleanWebpackPluginOptions),
// Lint the sources
new ESLintPlugin(ESLintPluginOptions),
new StylelintPlugin(StylelintPluginOptions),
// Add Vue
new VueLoaderPlugin(),
// Add Dojo
new DojoWebpackPlugin(DojoWebpackPluginOptions),
// dojo-webpack-plugin doesn't support domReady!
new webpack.NormalModuleReplacementPlugin(
/^dojo\/domReady!/,
NormalModuleReplacementPluginOptionsDomReady
),
new webpack.NormalModuleReplacementPlugin(/^dojo\/text!/, function (data) {
/* eslint-disable-next-line no-param-reassign */
data.request = data.request.replace(/^dojo\/text!/, "!!raw-loader!");
}),
// Copy a few Dojo ressources
new CopyWebpackPlugin(CopyWebpackPluginOptions),
// Handle SVG
new webpack.NormalModuleReplacementPlugin(
/^svg!/,
NormalModuleReplacementPluginOptionsSVG
),
// Handle CSS
new MiniCssExtractPlugin({
experimentalUseImportModule: false,
filename: "css/[name].css",
chunkFilename: "css/[id].css"
}),
// Handle HTML
new HtmlWebpackPlugin({
inject: false, // Tags are injected manually in the content below
minify: false, // Adjust t/16-schema-upgrade-html.t if prodMode is used,
filename: "ui-header.html",
mode: prodMode ? "production" : "development",
excludeChunks: [...Object.keys(lsmbCSS)],
template: "lib/ui-header.html"
}),
// Analyze the generated JS code. Use `npm run analyzer` to view
new BundleAnalyzerPlugin({
analyzerHost: "0.0.0.0",
analyzerMode: prodMode ? "disabled" : "json",
openAnalyzer: false,
generateStatsFile: !prodMode,
statsFilename: "../../logs/stats.json",
reportFilename: "../../logs/report.json"
}),
// Warn on duplication of code
new DuplicatesPlugin({
// Emit compilation warning or error? (Default: `false`)
emitErrors: false,
// Display full duplicates information? (Default: `false`)
verbose: true
}),
// Generate GZ versions of compiled code to sppedup download
new CompressionPlugin({
filename: "[path][base].gz",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
];
var pluginsDev = [
...pluginsProd,
new UnusedWebpackPlugin(UnusedWebpackPluginOptions),
new webpack.DefinePlugin({
"__VUE_OPTIONS_API__": true,
"__VUE_PROD_DEVTOOLS__": true
})
];
var pluginsList = prodMode ? pluginsProd : pluginsDev;
/* OPTIMIZATIONS */
const optimizationList = {
chunkIds: "named", // Keep names to load only 1 theme
emitOnErrors: false,
minimize: prodMode,
minimizer: [
new TerserPlugin({
parallel: parallelJobs
}),
new CssMinimizerPlugin({
parallel: parallelJobs
})
],
moduleIds: 'deterministic',
runtimeChunk: "multiple",
splitChunks: {
cacheGroups: {
node_modules: {
test(module) {
// `module.resource` contains the absolute path of the file on disk.
// Note the usage of `path.sep` instead of / or \, for cross-platform compatibility.
return (
module.resource &&
!module.resource.endsWith(".css") &&
module.resource.includes(
`${path.sep}node_modules${path.sep}`
)
);
},
name(module) {
const packageName = module.context.match(
/[\\/]node_modules[\\/](.*?)([\\/]|$)/
)[1];
return `npm.${packageName.replace("@", "")}`;
},
chunks: "all"
}
}
}
};
/* WEBPACK CONFIG */
const webpackConfigs = {
context: path.join(__dirname, "UI"),
entry: {
main: {
filename: "lsmb/main.js",
import: "lsmb/main",
dependOn: "dojo-shared"
},
"dojo-shared": [ ...includedRequires ],
...lsmbCSS
},
output: {
path: path.join(__dirname, "UI/js"), // js path
publicPath: "js/", // images path
pathinfo: !prodMode, // keep source references?
filename: "_scripts/[name].[contenthash].js",
chunkFilename: "_scripts/[name].[contenthash].js"
},
module: {
rules: [vue, javascript, css, images, svg, html]
},
plugins: pluginsList,
resolve: {
alias: {
// "vue": "@vue/runtime-dom",
"vue$": "vue/dist/vue.esm-bundler.js",
"@": path.join(__dirname, "UI/js-src/lsmb")
},
extensions: [ ".js", ".vue" ],
fallback: {
path: require.resolve("path-browserify")
}
},
resolveLoader: {
modules: ["node_modules"]
},
mode: process.env.NODE_ENV,
optimization: optimizationList,
performance: { hints: prodMode ? false : "warning" },
devtool: prodMode ? "hidden-source-map" : "source-map"
};
module.exports = webpackConfigs;
}
else{
const { merge } = require("webpack-merge");
/* Include Markdown compiling for README.md */
const WebpackCompileMarkdown = require("./UI/js-src/webpack-compile-markdown.js");
module.exports = merge({ entry: {}}, WebpackCompileMarkdown);
}