-
Notifications
You must be signed in to change notification settings - Fork 44
/
webpack.config.js
405 lines (373 loc) · 13.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
const path = require( 'path' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
const WooCommerceDependencyExtractionWebpackPlugin = require( '@woocommerce/dependency-extraction-webpack-plugin' );
const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
const TerserJSPlugin = require( 'terser-webpack-plugin' );
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const { omit } = require( 'lodash' );
const fs = require("fs");
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const glob = require( 'glob' );
const { paramCase } = require( 'change-case' );
// This is a simple webpack plugin to delete the JS files generated by MiniCssExtractPlugin.
function RemoveFilesPlugin( filePath = '' ) {
this.filePath = filePath;
}
RemoveFilesPlugin.prototype.apply = function ( compiler ) {
compiler.hooks.afterEmit.tap( 'afterEmit', () => {
const files = glob.sync( this.filePath );
files.forEach( ( f ) => {
fs.unlink( f, ( err ) => {
if ( err ) {
/* eslint-disable-next-line no-console */
console.log( `There was an error removing ${ f }.`, err );
}
} );
} );
} );
};
function findModuleMatch( module, match ) {
if ( module.request && match.test( module.request ) ) {
return true;
} else if ( module.issuer ) {
return findModuleMatch( module.issuer, match );
}
return false;
}
// Remove SASS rule from the default config so we can define our own.
const defaultRules = defaultConfig.module.rules.filter( ( rule ) => {
return String( rule.test ) !== String( /\.(sc|sa)ss$/ );
} );
const blocks = {
'checkout': {},
'cart': {},
'mini-cart': {},
};
const getBlockEntries = ( relativePath ) => {
return Object.fromEntries(
Object.entries( blocks )
.map( ( [ blockCode, config ] ) => {
const filePaths = glob.sync(
`./assets/js/blocks/${ config.customDir || blockCode }/` +
relativePath
);
if ( filePaths.length > 0 ) {
return [ blockCode, filePaths ];
}
return null;
} )
.filter( Boolean )
);
};
const staticCss = glob.sync('./assets/css/*.scss').reduce(function(obj, el){
obj[ path.parse(el).name + '-styles' ] = el;
return obj
},{});
const staticJs = glob.sync('./assets/js/static/*.js').reduce(function(obj, el){
obj[ path.parse(el).name ] = el;
return obj
},{});
const staticEntry = { ...staticCss, ...staticJs }
const entries = {
'static': staticEntry,
styling: {
// Shared blocks code
'wc-gzd-blocks': './assets/js/index.js',
'wc-gzd-blocks-product-elements': './assets/js/blocks/product-elements/index.js',
...getBlockEntries( '{index,block,frontend}.{t,j}s{,x}' ),
},
core: {
wcGzdBlocksSettings: './assets/js/settings/index.js',
},
main: {
// Shared blocks code
'wc-gzd-blocks': './assets/js/index.js',
// Blocks
...getBlockEntries( 'index.{t,j}s{,x}' )
},
frontend: {
// Shared blocks code
'wc-gzd-blocks': './assets/js/frontend.js',
...getBlockEntries( 'frontend.{t,j}s{,x}' ),
},
productElements: {
'wc-gzd-blocks-product-elements': './assets/js/blocks/product-elements/index.js',
},
payments: {
'wc-gzd-payment-method-invoice': './assets/js/payment-methods/invoice/index.js',
'wc-gzd-payment-method-direct-debit': './assets/js/payment-methods/direct-debit/index.js',
},
};
const getEntryConfig = ( type = 'main', exclude = [] ) => {
return omit( entries[ type ], exclude );
};
const getAlias = ( options = {} ) => {
return {
'@germanized/product-elements': path.resolve(
__dirname,
`/assets/js/blocks/product-elements/`
),
'@germanized/base-components': path.resolve(
__dirname,
`/assets/js/base/components/`
),
'@germanized/base-hooks': path.resolve(
__dirname,
`/assets/js/base/hooks/`
),
'@germanized/types': path.resolve(
__dirname,
`/assets/js/types/`
),
'@germanized/settings': path.resolve(
__dirname,
`/assets/js/settings`
),
};
};
const wcDepMap = {
'@woocommerce/blocks-registry': [ 'wc', 'wcBlocksRegistry' ],
'@woocommerce/settings': [ 'wc', 'wcSettings' ],
'@woocommerce/block-data': [ 'wc', 'wcBlocksData' ],
'@woocommerce/data': [ 'wc', 'data' ],
'@woocommerce/shared-context': [ 'wc', 'wcBlocksSharedContext' ],
'@woocommerce/shared-hocs': [ 'wc', 'wcBlocksSharedHocs' ],
'@woocommerce/price-format': [ 'wc', 'priceFormat' ],
'@woocommerce/blocks-checkout': [ 'wc', 'blocksCheckout' ],
'@woocommerce/interactivity': [ 'wc', '__experimentalInteractivity' ],
'@germanized/settings': [ 'wcGzd', 'blocks', 'wcGzdBlocksSettings' ]
};
const wcHandleMap = {
'@woocommerce/blocks-registry': 'wc-blocks-registry',
'@woocommerce/settings': 'wc-settings',
'@woocommerce/block-data': 'wc-blocks-data-store',
'@woocommerce/data': 'wc-store-data',
'@woocommerce/shared-context': 'wc-blocks-shared-context',
'@woocommerce/shared-hocs': 'wc-blocks-shared-hocs',
'@woocommerce/price-format': 'wc-price-format',
'@woocommerce/blocks-checkout': 'wc-blocks-checkout',
'@woocommerce/interactivity': 'wc-interactivity',
'@germanized/settings': 'wc-gzd-blocks-settings'
};
const requestToExternal = ( request ) => {
if ( wcDepMap[ request ] ) {
return wcDepMap[ request ];
}
};
const requestToHandle = ( request ) => {
if ( wcHandleMap[ request ] ) {
return wcHandleMap[ request ];
}
};
const getBaseConfig = ( entry ) => {
return {
...defaultConfig,
entry: getEntryConfig( entry, [] ),
output: {
filename: ( chunkData ) => {
return `${ paramCase( chunkData.chunk.name ) }.js`;
},
path: path.resolve( __dirname, 'build/' ),
library: [ 'wcGzd', 'blocks', '[name]' ],
libraryTarget: 'window',
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
chunkLoadingGlobal: 'webpackWcGzdBlocksJsonp',
},
module: {
...defaultConfig.module,
rules: [
...defaultRules,
{
test: /\.(sc|sa)ss$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: [ 'assets/css' ],
},
additionalData: ( content, loaderContext ) => {
const {
resourcePath,
rootContext,
} = loaderContext;
const relativePath = path.relative(
rootContext,
resourcePath
);
if (
relativePath.startsWith( 'assets/css/' )
) {
return content;
}
// Add code here to prepend to all .scss/.sass files.
return (
content
);
},
},
},
],
},
],
},
resolve: {
alias: getAlias()
},
plugins: [
...defaultConfig.plugins.filter(
( plugin ) =>
plugin.constructor.name !== 'DependencyExtractionWebpackPlugin'
),
new WooCommerceDependencyExtractionWebpackPlugin( {
requestToExternal,
requestToHandle,
} ),
new MiniCssExtractPlugin( {
filename: `[name].css`,
} ),
],
};
};
const CoreConfig = {
...getBaseConfig( 'core' )
};
const ProductElements = {
...getBaseConfig( 'productElements' )
};
const PaymentsConfig = {
...getBaseConfig( 'payments' )
};
const innerMainConfig = getBaseConfig( 'main' );
const MainConfig = {
...innerMainConfig,
plugins: [
...innerMainConfig.plugins,
new CopyWebpackPlugin( {
patterns: [
{
from: './assets/js/**/block.json',
to( { absoluteFilename } ) {
/**
* Getting the block name from the JSON metadata is less error prone
* than extracting it from the file path.
*/
const JSONFile = fs.readFileSync(
path.resolve( __dirname, absoluteFilename )
);
const metadata = JSON.parse( JSONFile.toString() );
const blockName = metadata.name
.split( '/' )
.at( 1 );
if ( metadata.parent )
return `./inner-blocks/${ blockName }/block.json`;
return `./${ blockName }/block.json`;
},
},
],
} ),
],
};
const FrontendConfig = {
...getBaseConfig( 'frontend' ),
output: {
devtoolNamespace: 'wcGzd',
path: path.resolve( __dirname, 'build/' ),
// This is a cache busting mechanism which ensures that the script is loaded via the browser with a ?ver=hash
// string. The hash is based on the built file contents.
// @see https://github.com/webpack/webpack/issues/2329
// Using the ?ver string is needed here so the filename does not change between builds. The WordPress
// i18n system relies on the hash of the filename, so changing that frequently would result in broken
// translations which we must avoid.
// @see https://github.com/Automattic/jetpack/pull/20926
chunkFilename: `[name]-frontend.js?ver=[contenthash]`,
filename: `[name]-frontend.js`,
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
// This can be removed when moving to webpack 5:
// https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
chunkLoadingGlobal: 'webpackWcBlocksJsonp',
}
};
const innerStylingConfig = getBaseConfig( 'styling' );
const StylingConfig = {
...innerStylingConfig,
optimization: {
splitChunks: {
minSize: 0,
automaticNameDelimiter: '--',
cacheGroups: {
editorStyle: {
// Capture all `editor` stylesheets and editor-components stylesheets.
test: ( module = {} ) =>
module.constructor.name === 'CssModule' &&
( findModuleMatch( module, /editor\.scss$/ ) ||
findModuleMatch(
module,
/[\\/]assets[\\/]js[\\/]editor-components[\\/]/
) ),
name: 'wc-gzd-blocks-editor-style',
chunks: 'all',
priority: 10,
},
},
},
},
output: {
devtoolNamespace: 'wcGzd',
path: path.resolve( __dirname, 'build/' ),
filename: `[name]-style.js`,
library: [ 'wcGzd', 'blocks', '[name]' ],
libraryTarget: 'window',
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
// This can be removed when moving to webpack 5:
// https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
chunkLoadingGlobal: 'webpackWcGzdBlocksJsonp'
},
resolve: {
alias: getAlias(),
extensions: [ '.js' ],
},
plugins: [
...innerStylingConfig.plugins,
// Remove JS files generated by MiniCssExtractPlugin.
new RemoveFilesPlugin( `./build/*style.js` ),
],
};
const StaticConfig = {
...defaultConfig,
entry: getEntryConfig( 'static', [] ),
resolve: {
extensions: ['.js', '.css', '.scss']
},
optimization: {
minimizer: [
new CssMinimizerPlugin(),
],
minimize: true,
},
output: {
path: path.resolve( __dirname, './build/static/' ),
filename: "[name].js",
devtoolNamespace: 'germanized',
library: [ 'germanized', 'static', '[name]' ],
libraryTarget: 'window',
}
};
module.exports = [
CoreConfig,
MainConfig,
FrontendConfig,
ProductElements,
PaymentsConfig,
StylingConfig,
StaticConfig
];