-
Notifications
You must be signed in to change notification settings - Fork 178
/
webpack.config.cjs
496 lines (472 loc) · 14.3 KB
/
webpack.config.cjs
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
489
490
491
492
493
494
495
496
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
const { readdirSync } = require('fs');
const { resolve, parse } = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const RtlCssPlugin = require('rtlcss-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const WebpackBar = require('webpackbar');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
/**
* WordPress dependencies
*/
const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extraction-webpack-plugin');
/**
* Prevents externalizing certain packages.
*
* @param {string} request Requested module
* @return {(string|undefined|boolean)} Script global
*/
function requestToExternal(request) {
const packages = ['react', 'react-dom', 'react-dom/server'];
if (packages.includes(request)) {
return false;
}
if (request.includes('react-refresh/runtime')) {
return false;
}
return undefined;
}
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const isProduction = process.env.NODE_ENV === 'production';
const mode = isProduction ? 'production' : 'development';
const sharedConfig = {
resolve: {
// Fixes resolving packages in the monorepo so we use the "src" folder, not "dist".
exportsFields: ['customExports', 'exports'],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.wasm'],
// To make loading mediainfo.js work.
fallback: {
fs: false,
path: false,
url: false,
module: false,
assert: false,
perf_hooks: false,
},
},
mode,
devtool: !isProduction ? 'source-map' : undefined,
output: {
path: resolve(process.cwd(), 'assets', 'js'),
filename: '[name].js',
chunkFilename: '[name].js?v=[chunkhash]',
publicPath: '',
},
target: 'browserslist',
module: {
rules: [
!isProduction && {
test: /\.m?js$/,
use: ['source-map-loader'],
// html-to-image and react-blurhash reference source maps but don't currently ship with any.
exclude: /node_modules\/html-to-image|node_modules\/react-blurhash/,
enforce: 'pre',
resolve: {
fullySpecified: false,
},
},
{
test: /\.worker\.([jt])s$/,
exclude: /node_modules/,
use: {
loader: 'worker-loader',
options: {
inline: 'fallback',
},
},
},
{
test: /\.([jt])sx?$/,
exclude: /node_modules/,
resolve: {
// Avoid having to provide full file extension for imports.
// See https://webpack.js.org/configuration/module/#resolvefullyspecified
fullySpecified: false,
},
use: [
{
loader: '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,
plugins: [
!isProduction && require.resolve('react-refresh/babel'),
].filter(Boolean),
},
},
],
},
// These should be sync'd with the config in `.storybook/main.cjs`.
{
test: /\.svg$/,
// Use asset SVG and SVGR together.
// Not using resourceQuery because it doesn't work well with Rollup.
// https://react-svgr.com/docs/webpack/#use-svgr-and-asset-svg-in-the-same-project
oneOf: [
{
type: 'asset/inline',
include: [/inline-icons\/.*\.svg$/],
},
{
issuer: /\.[jt]sx?$/,
include: [/\/icons\/.*\.svg$/],
use: [
{
loader: '@svgr/webpack',
options: {
titleProp: true,
svgo: true,
memo: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
convertColors: {
currentColor: /^(?!url|none)/i,
},
},
},
},
'removeDimensions',
],
},
},
},
],
},
{
issuer: /\.[jt]sx?$/,
include: [/images\/.*\.svg$/],
use: [
{
loader: '@svgr/webpack',
options: {
titleProp: true,
svgo: true,
memo: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
convertColors: {
// See https://github.com/googleforcreators/web-stories-wp/pull/6361
currentColor: false,
},
},
},
},
'removeDimensions',
],
},
},
},
],
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
sideEffects: true,
},
{
test: /\.(png|jpe?g|gif|webp)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[hash][ext]',
},
},
].filter(Boolean),
},
plugins: [
process.env.BUNDLE_ANALYZER &&
new BundleAnalyzerPlugin({
analyzerPort: 'auto',
}),
new MiniCssExtractPlugin({
filename: '../css/[name].css',
}),
new RtlCssPlugin({
filename: `../css/[name]-rtl.css`,
}),
new webpack.DefinePlugin({
WEB_STORIES_CI: JSON.stringify(process.env.CI),
WEB_STORIES_ENV: JSON.stringify(process.env.NODE_ENV),
WEB_STORIES_DISABLE_ERROR_BOUNDARIES: JSON.stringify(
process.env.DISABLE_ERROR_BOUNDARIES
),
WEB_STORIES_DISABLE_OPTIMIZED_RENDERING: JSON.stringify(
process.env.DISABLE_OPTIMIZED_RENDERING
),
WEB_STORIES_DISABLE_PREVENT: JSON.stringify(process.env.DISABLE_PREVENT),
WEB_STORIES_DISABLE_QUICK_TIPS: JSON.stringify(
process.env.DISABLE_QUICK_TIPS
),
}),
new DependencyExtractionWebpackPlugin(),
!isProduction &&
new CircularDependencyPlugin({
// exclude detection of files based on a RegExp
include: /packages/,
// add errors to webpack instead of warnings
failOnError: true,
// allow import cycles that include an asynchronous import,
// e.g. via import(/* webpackMode: "weak" */ './file.js')
allowAsyncCycles: false,
// set the current working directory for displaying module paths
cwd: process.cwd(),
}),
].filter(Boolean),
optimization: {
sideEffects: true,
splitChunks: {
automaticNameDelimiter: '-',
},
mangleExports: false,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
// We preserve function names that start with capital letters as
// they're _likely_ component names, and these are useful to have
// in tracebacks and error messages.
keep_fnames: /__|_x|_n|_nx|sprintf|^[A-Z].+$/,
output: {
comments: /translators:/i,
},
},
extractComments: false,
}),
new CssMinimizerPlugin(),
],
},
};
const EDITOR_CHUNK = 'web-stories-editor';
const DASHBOARD_CHUNK = 'web-stories-dashboard';
// Template for html-webpack-plugin to generate JS/CSS chunk manifests in PHP.
const templateContent = ({ htmlWebpackPlugin, chunkNames }) => {
// Extract filename without extension from arrays of JS and CSS chunks.
// E.g. "../css/some-chunk.css" -> "some-chunk"
const filenameOf = (pathname) =>
pathname.substr(pathname.lastIndexOf('/') + 1);
const chunkName = htmlWebpackPlugin.options.chunks[0];
const omitPrimaryChunk = (f) => f !== chunkName;
const omitRightToLeftChunk = (f) => !f.endsWith('-rtl');
const js = htmlWebpackPlugin.files.js
.map((pathname) => {
const f = filenameOf(pathname);
return f.split('.js')[0];
})
.filter(omitPrimaryChunk);
const css = htmlWebpackPlugin.files.css
.map((pathname) => {
const f = filenameOf(pathname);
return f.split('.css')[0];
})
.filter(omitPrimaryChunk)
.filter(omitRightToLeftChunk);
// We're only interested in chunks from dynamic imports;
// ones that are not already in `js` and not primaries.
const chunks = chunkNames.filter(
(chunk) =>
!js.includes(chunk) && ![DASHBOARD_CHUNK, EDITOR_CHUNK].includes(chunk)
);
return `<?php
return [
'css' => ${JSON.stringify(css)},
'js' => ${JSON.stringify(js)},
'chunks' => ${JSON.stringify(chunks)},
];`;
};
const templateParameters = (compilation, assets, assetTags, options) => ({
compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options,
},
// compilation.chunks is a Set.
chunkNames: [...compilation.chunks].map(({ name }) => name).filter(Boolean),
});
const editorAndDashboard = {
...sharedConfig,
devServer: !isProduction
? {
devMiddleware: {
writeToDisk: true,
},
hot: true,
allowedHosts: 'all',
host: 'localhost',
port: 'auto',
}
: undefined,
entry: {
[EDITOR_CHUNK]: './packages/wp-story-editor/src/index.js',
[DASHBOARD_CHUNK]: './packages/wp-dashboard/src/index.js',
},
plugins: [
...sharedConfig.plugins.filter(
(plugin) => !(plugin instanceof DependencyExtractionWebpackPlugin)
),
// React Fast Refresh.
!isProduction && new ReactRefreshWebpackPlugin(),
new DependencyExtractionWebpackPlugin({
requestToExternal,
}),
new WebpackBar({
name: 'Editor & Dashboard',
}),
new HtmlWebpackPlugin({
filename: `${EDITOR_CHUNK}.chunks.php`,
inject: false, // Don't inject default <script> tags, etc.
minify: false, // PHP not HTML so don't attempt to minify.
chunks: [EDITOR_CHUNK],
templateContent,
templateParameters,
}),
new HtmlWebpackPlugin({
filename: `${DASHBOARD_CHUNK}.chunks.php`,
inject: false, // Don't inject default <script> tags, etc.
minify: false, // PHP not HTML so don't attempt to minify.
chunks: [DASHBOARD_CHUNK],
templateContent,
templateParameters,
}),
].filter(Boolean),
optimization: {
...sharedConfig.optimization,
splitChunks: {
...sharedConfig.optimization.splitChunks,
chunks: 'all',
},
},
};
const webStoriesScripts = {
...sharedConfig,
entry: {
'web-stories-lightbox': './packages/stories-lightbox/src/index.js',
'web-stories-carousel': './packages/stories-carousel/src/index.js',
},
plugins: [
...sharedConfig.plugins,
new WebpackBar({
name: 'WP Frontend Scripts',
color: '#EEE070',
}),
].filter(Boolean),
};
// Collect all core themes style sheet paths.
const coreThemesBlockStylesPaths = readdirSync(
'./packages/stories-block/src/css/core-themes'
);
// Build entry object for the Core Themes Styles.
const coreThemeBlockStyles = coreThemesBlockStylesPaths.reduce((acc, curr) => {
const fileName = parse(curr).name;
return {
...acc,
[`web-stories-theme-style-${fileName}`]: `./packages/stories-block/src/css/core-themes/${curr}`,
};
}, {});
const webStoriesBlock = {
...sharedConfig,
entry: {
'web-stories-block': [
'./packages/stories-block/src/index.js',
'./packages/stories-block/src/block/edit.css',
],
'web-stories-list-styles': './packages/stories-block/src/css/style.css',
'web-stories-embed': './packages/stories-block/src/css/embed.css',
...coreThemeBlockStyles,
},
plugins: [
...sharedConfig.plugins,
// React Fast Refresh.
!isProduction && new ReactRefreshWebpackPlugin(),
new WebpackBar({
name: 'Web Stories Block',
color: '#357BB5',
}),
].filter(Boolean),
};
const activationNotice = {
...sharedConfig,
entry: {
'web-stories-activation-notice':
'./packages/activation-notice/src/index.tsx',
},
plugins: [
...sharedConfig.plugins,
// React Fast Refresh.
!isProduction && new ReactRefreshWebpackPlugin(),
new WebpackBar({
name: 'Activation Notice',
color: '#fcd8ba',
}),
].filter(Boolean),
};
const widgetScript = {
...sharedConfig,
entry: {
'web-stories-widget': './packages/widget/src/index.js',
},
plugins: [
...sharedConfig.plugins,
new WebpackBar({
name: 'WP Widget Script',
color: '#F757A5',
}),
].filter(Boolean),
};
const storiesMCEButton = {
...sharedConfig,
entry: {
'web-stories-tinymce-button': './packages/tinymce-button/src/index.js',
},
plugins: [
...sharedConfig.plugins,
new WebpackBar({
name: 'WP TinyMCE Button',
color: '#4deaa2',
}),
].filter(Boolean),
};
module.exports = [
editorAndDashboard,
activationNotice,
webStoriesBlock,
webStoriesScripts,
widgetScript,
storiesMCEButton,
];