-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathwebpack.config.js
314 lines (302 loc) · 7.75 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
/**
* External dependencies
*/
const { BundleAnalyzerPlugin } = require( 'webpack-bundle-analyzer' );
const { CleanWebpackPlugin } = require( 'clean-webpack-plugin' );
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const browserslist = require( 'browserslist' );
const MiniCSSExtractPlugin = require( 'mini-css-extract-plugin' );
const { basename, dirname, resolve } = require( 'path' );
const ReactRefreshWebpackPlugin = require( '@pmmmwh/react-refresh-webpack-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
/**
* WordPress dependencies
*/
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
const postcssPlugins = require( '@wordpress/postcss-plugins-preset' );
/**
* Internal dependencies
*/
const {
fromConfigRoot,
hasBabelConfig,
hasArgInCLI,
hasCssnanoConfig,
hasPostCSSConfig,
getWebpackEntryPoints,
} = 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 copyWebpackPatterns = process.env.WP_COPY_PHP_FILES_TO_DIST
? '**/{block.json,*.php}'
: '**/block.json';
const cssLoaders = [
{
loader: MiniCSSExtractPlugin.loader,
},
{
loader: require.resolve( 'css-loader' ),
options: {
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,
},
} ),
},
},
];
const config = {
mode,
target,
entry: getWebpackEntryPoints,
output: {
filename: '[name].js',
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,
splitChunks: {
cacheGroups: {
style: {
type: 'css/mini-extract',
test: /[\\/]style(\.module)?\.(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: /\.(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: /\.(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: /\.(sc|sa|c)ss$/,
type: 'asset/inline',
},
{
test: /\.(bmp|png|jpe?g|gif)$/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]',
},
},
],
},
plugins: [
// During rebuilds, all webpack assets that are not used anymore will be
// removed automatically. There is an exception added in watch mode for
// fonts and images. It is a known limitations:
// https://github.com/johnagan/clean-webpack-plugin/issues/159
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 CopyWebpackPlugin( {
patterns: [
{
from: copyWebpackPatterns,
context: process.env.WP_SRC_DIRECTORY,
noErrorOnMissing: true,
transform( content, absoluteFrom ) {
const convertExtension = ( path ) => {
return path.replace( /\.(j|t)sx?$/, '.js' );
};
if ( basename( absoluteFrom ) === 'block.json' ) {
const blockJson = JSON.parse( content.toString() );
[ 'viewScript', 'script', 'editorScript' ].forEach(
( key ) => {
if ( Array.isArray( blockJson[ key ] ) ) {
blockJson[ key ] =
blockJson[ key ].map(
convertExtension
);
} else if (
typeof blockJson[ key ] === 'string'
) {
blockJson[ key ] = convertExtension(
blockJson[ key ]
);
}
}
);
return JSON.stringify( blockJson, null, 2 );
}
return content;
},
},
],
} ),
// 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' } ),
// 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 ),
stats: {
children: false,
},
};
if ( ! isProduction ) {
// WP_DEVTOOL global variable controls how source maps are generated.
// See: https://webpack.js.org/configuration/devtool/#devtool.
config.devtool = process.env.WP_DEVTOOL || 'source-map';
config.module.rules.unshift( {
test: /\.(j|t)sx?$/,
exclude: [ /node_modules/ ],
use: require.resolve( 'source-map-loader' ),
enforce: 'pre',
} );
config.devServer = {
devMiddleware: {
writeToDisk: true,
},
allowedHosts: 'auto',
host: 'localhost',
port: 8887,
proxy: {
'/build': {
pathRewrite: {
'^/build': '',
},
},
},
};
}
module.exports = config;