-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
webpack.config.js
488 lines (460 loc) · 12.3 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
/**
* External dependencies
*/
const { BundleAnalyzerPlugin } = require( 'webpack-bundle-analyzer' );
const { CleanWebpackPlugin } = require( 'clean-webpack-plugin' );
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const webpack = require( 'webpack' );
const browserslist = require( 'browserslist' );
const MiniCSSExtractPlugin = require( 'mini-css-extract-plugin' );
const { basename, dirname, relative, resolve, sep } = require( 'path' );
const ReactRefreshWebpackPlugin = require( '@pmmmwh/react-refresh-webpack-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
const { realpathSync } = require( 'fs' );
const { sync: glob } = require( 'fast-glob' );
/**
* WordPress dependencies
*/
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
const postcssPlugins = require( '@wordpress/postcss-plugins-preset' );
/**
* Internal dependencies
*/
const PhpFilePathsPlugin = require( '../plugins/php-file-paths-plugin' );
const RtlCssPlugin = require( '../plugins/rtlcss-webpack-plugin' );
const {
fromConfigRoot,
hasBabelConfig,
hasArgInCLI,
hasCssnanoConfig,
hasPostCSSConfig,
getProjectSourcePath,
getWebpackEntryPoints,
getAsBooleanFromENV,
getBlockJsonModuleFields,
getBlockJsonScriptFields,
fromProjectRoot,
} = require( '../utils' );
const isProduction = process.env.NODE_ENV === 'production';
const mode = isProduction ? 'production' : 'development';
let target = 'browserslist';
if ( ! browserslist.findConfig( '.' ) ) {
target += ':' + fromConfigRoot( '.browserslistrc' );
}
const hasReactFastRefresh = hasArgInCLI( '--hot' ) && ! isProduction;
const hasExperimentalModulesFlag = getAsBooleanFromENV(
'WP_EXPERIMENTAL_MODULES'
);
const cssLoaders = [
{
loader: MiniCSSExtractPlugin.loader,
},
{
loader: require.resolve( 'css-loader' ),
options: {
importLoaders: 1,
sourceMap: ! isProduction,
modules: {
auto: true,
},
},
},
{
loader: require.resolve( 'postcss-loader' ),
options: {
// Provide a fallback configuration if there's not
// one explicitly available in the project.
...( ! hasPostCSSConfig() && {
postcssOptions: {
ident: 'postcss',
sourceMap: ! isProduction,
plugins: isProduction
? [
...postcssPlugins,
require( 'cssnano' )( {
// Provide a fallback configuration if there's not
// one explicitly available in the project.
...( ! hasCssnanoConfig() && {
preset: [
'default',
{
discardComments: {
removeAll: true,
},
},
],
} ),
} ),
]
: postcssPlugins,
},
} ),
},
},
];
/** @type {webpack.Configuration} */
const baseConfig = {
mode,
target,
output: {
filename: '[name].js',
chunkFilename: '[name].js?ver=[chunkhash]',
path: resolve( process.cwd(), 'build' ),
},
resolve: {
alias: {
'lodash-es': 'lodash',
},
extensions: [ '.jsx', '.ts', '.tsx', '...' ],
},
optimization: {
// Only concatenate modules in production, when not analyzing bundles.
concatenateModules: isProduction && ! process.env.WP_BUNDLE_ANALYZER,
runtimeChunk: hasReactFastRefresh && 'single',
splitChunks: {
cacheGroups: {
style: {
type: 'css/mini-extract',
test: /[\\/]style(\.module)?\.(pc|sc|sa|c)ss$/,
chunks: 'all',
enforce: true,
name( _, chunks, cacheGroupKey ) {
const chunkName = chunks[ 0 ].name;
return `${ dirname(
chunkName
) }/${ cacheGroupKey }-${ basename( chunkName ) }`;
},
},
default: false,
},
},
minimizer: [
new TerserPlugin( {
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
module: {
rules: [
{
test: /\.m?(j|t)sx?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve( 'babel-loader' ),
options: {
// Babel uses a directory within local node_modules
// by default. Use the environment variable option
// to enable more persistent caching.
cacheDirectory:
process.env.BABEL_CACHE_DIRECTORY || true,
// Provide a fallback configuration if there's not
// one explicitly available in the project.
...( ! hasBabelConfig() && {
babelrc: false,
configFile: false,
presets: [
require.resolve(
'@wordpress/babel-preset-default'
),
],
plugins: [
hasReactFastRefresh &&
require.resolve(
'react-refresh/babel'
),
].filter( Boolean ),
} ),
},
},
],
},
{
test: /\.css$/,
use: cssLoaders,
},
{
test: /\.pcss$/,
use: cssLoaders,
},
{
test: /\.(sc|sa)ss$/,
use: [
...cssLoaders,
{
loader: require.resolve( 'sass-loader' ),
options: {
sourceMap: ! isProduction,
},
},
],
},
{
test: /\.svg$/,
issuer: /\.(j|t)sx?$/,
use: [ '@svgr/webpack', 'url-loader' ],
type: 'javascript/auto',
},
{
test: /\.svg$/,
issuer: /\.(pc|sc|sa|c)ss$/,
type: 'asset/inline',
},
{
test: /\.(bmp|png|jpe?g|gif|webp)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[name].[hash:8][ext]',
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'fonts/[name].[hash:8][ext]',
},
},
],
},
stats: {
children: false,
},
};
// WP_DEVTOOL global variable controls how source maps are generated.
// See: https://webpack.js.org/configuration/devtool/#devtool.
if ( process.env.WP_DEVTOOL ) {
baseConfig.devtool = process.env.WP_DEVTOOL;
}
if ( ! isProduction ) {
// Set default sourcemap mode if it wasn't set by WP_DEVTOOL.
baseConfig.devtool = baseConfig.devtool || 'source-map';
}
// Add source-map-loader if devtool is set, whether in dev mode or not.
if ( baseConfig.devtool ) {
baseConfig.module.rules.unshift( {
test: /\.(j|t)sx?$/,
exclude: [ /node_modules/ ],
use: require.resolve( 'source-map-loader' ),
enforce: 'pre',
} );
}
/** @type {webpack.Configuration} */
const scriptConfig = {
...baseConfig,
entry: getWebpackEntryPoints( 'script' ),
devServer: isProduction
? undefined
: {
devMiddleware: {
writeToDisk: true,
},
allowedHosts: 'auto',
host: 'localhost',
port: 8887,
proxy: {
'/build': {
pathRewrite: {
'^/build': '',
},
},
},
},
plugins: [
new webpack.DefinePlugin( {
// Inject the `SCRIPT_DEBUG` global, used for development features flagging.
'globalThis.SCRIPT_DEBUG': JSON.stringify( ! isProduction ),
SCRIPT_DEBUG: JSON.stringify( ! isProduction ),
} ),
// If we run a modules build, the 2 compilations can "clean" each other's output
// Prevent the cleaning from happening
! hasExperimentalModulesFlag &&
new CleanWebpackPlugin( {
cleanAfterEveryBuildPatterns: [ '!fonts/**', '!images/**' ],
// Prevent it from deleting webpack assets during builds that have
// multiple configurations returned in the webpack config.
cleanStaleWebpackAssets: false,
} ),
new PhpFilePathsPlugin( {
context: getProjectSourcePath(),
props: [ 'render', 'variations' ],
} ),
new CopyWebpackPlugin( {
patterns: [
{
from: '**/block.json',
context: getProjectSourcePath(),
noErrorOnMissing: true,
transform( content, absoluteFrom ) {
const convertExtension = ( path ) => {
return path.replace( /\.m?(j|t)sx?$/, '.js' );
};
if ( basename( absoluteFrom ) === 'block.json' ) {
const blockJson = JSON.parse( content.toString() );
[
getBlockJsonScriptFields( blockJson ),
getBlockJsonModuleFields( blockJson ),
].forEach( ( fields ) => {
if ( fields ) {
for ( const [
key,
value,
] of Object.entries( fields ) ) {
if ( Array.isArray( value ) ) {
blockJson[ key ] =
value.map( convertExtension );
} else if (
typeof value === 'string'
) {
blockJson[ key ] =
convertExtension( value );
}
}
}
} );
if ( hasReactFastRefresh ) {
// Prepends the file reference to the shared runtime chunk to every script type defined for the block.
const runtimePath = relative(
dirname( absoluteFrom ),
fromProjectRoot(
getProjectSourcePath() +
sep +
'runtime.js'
)
);
const fields =
getBlockJsonScriptFields( blockJson );
for ( const [ fieldName ] of Object.entries(
fields
) ) {
blockJson[ fieldName ] = [
`file:${ runtimePath }`,
...( Array.isArray(
blockJson[ fieldName ]
)
? blockJson[ fieldName ]
: [ blockJson[ fieldName ] ] ),
];
}
}
return JSON.stringify( blockJson, null, 2 );
}
return content;
},
},
{
from: '**/*.php',
context: getProjectSourcePath(),
noErrorOnMissing: true,
filter: ( filepath ) => {
return (
process.env.WP_COPY_PHP_FILES_TO_DIST ||
PhpFilePathsPlugin.paths.includes(
realpathSync( filepath ).replace( /\\/g, '/' )
)
);
},
},
],
} ),
// The WP_BUNDLE_ANALYZER global variable enables a utility that represents
// bundle content as a convenient interactive zoomable treemap.
process.env.WP_BUNDLE_ANALYZER && new BundleAnalyzerPlugin(),
// MiniCSSExtractPlugin to extract the CSS thats gets imported into JavaScript.
new MiniCSSExtractPlugin( {
filename: '[name].css',
} ),
// RtlCssPlugin to generate RTL CSS files.
new RtlCssPlugin(),
// React Fast Refresh.
hasReactFastRefresh && new ReactRefreshWebpackPlugin(),
// WP_NO_EXTERNALS global variable controls whether scripts' assets get
// generated, and the default externals set.
! process.env.WP_NO_EXTERNALS &&
new DependencyExtractionWebpackPlugin(),
].filter( Boolean ),
};
if ( hasExperimentalModulesFlag ) {
/**
* Add block.json files to compilation to ensure changes trigger rebuilds when watching
*/
class BlockJsonDependenciesPlugin {
constructor() {
/** @type {ReadonlyArray<string>} */
this.blockJsonFiles = glob( '**/block.json', {
absolute: true,
cwd: fromProjectRoot( getProjectSourcePath() ),
} );
}
/**
* Apply the plugin
* @param {webpack.Compiler} compiler the compiler instance
* @return {void}
*/
apply( compiler ) {
if ( this.blockJsonFiles.length ) {
compiler.hooks.compilation.tap(
'BlockJsonDependenciesPlugin',
( compilation ) => {
compilation.fileDependencies.addAll(
this.blockJsonFiles
);
}
);
}
}
}
/** @type {webpack.Configuration} */
const moduleConfig = {
...baseConfig,
entry: getWebpackEntryPoints( 'module' ),
experiments: {
...baseConfig.experiments,
outputModule: true,
},
output: {
...baseConfig.output,
module: true,
chunkFormat: 'module',
environment: {
...baseConfig.output.environment,
module: true,
},
library: {
...baseConfig.output.library,
type: 'module',
},
},
plugins: [
new webpack.DefinePlugin( {
// Inject the `SCRIPT_DEBUG` global, used for development features flagging.
'globalThis.SCRIPT_DEBUG': JSON.stringify( ! isProduction ),
SCRIPT_DEBUG: JSON.stringify( ! isProduction ),
} ),
// The WP_BUNDLE_ANALYZER global variable enables a utility that represents
// bundle content as a convenient interactive zoomable treemap.
process.env.WP_BUNDLE_ANALYZER && new BundleAnalyzerPlugin(),
// MiniCSSExtractPlugin to extract the CSS thats gets imported into JavaScript.
new MiniCSSExtractPlugin( { filename: '[name].css' } ),
// WP_NO_EXTERNALS global variable controls whether scripts' assets get
// generated, and the default externals set.
! process.env.WP_NO_EXTERNALS &&
new DependencyExtractionWebpackPlugin(),
new BlockJsonDependenciesPlugin(),
].filter( Boolean ),
};
module.exports = [ scriptConfig, moduleConfig ];
} else {
module.exports = scriptConfig;
}