-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathwebpack.config.js
More file actions
215 lines (188 loc) · 6.79 KB
/
Copy pathwebpack.config.js
File metadata and controls
215 lines (188 loc) · 6.79 KB
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
/**
* Custom webpack configuration extending WordPress Scripts
*
* This configuration:
* - Places dynamic JS chunks in their source directory structure (src/foo/ → build/foo/).
* - Handles classic app vendor chunks separately.
* - Classifies script-module imports as import-map modules, wp-admin globals, or bundled packages.
*/
const path = require( 'path' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
const PROJECT_SOURCE_DIR = path.resolve( __dirname, 'src' );
// The admin app is loaded as script modules, but many WordPress packages it uses
// are still provided to wp-admin as classic `wp-*` scripts. Keep those imports
// externalized to the existing `window.wp.*` globals so module chunks do not
// bundle duplicate stores or private API instances.
const WORDPRESS_SCRIPT_GLOBALS = {
lodash: 'lodash',
'lodash-es': 'lodash',
moment: 'moment',
react: 'React',
'react-dom': 'ReactDOM',
'react-dom/client': 'ReactDOM',
'react/jsx-runtime': 'ReactJSXRuntime',
'react/jsx-dev-runtime': 'ReactJSXRuntime',
'@wordpress/api-fetch': [ 'wp', 'apiFetch' ],
'@wordpress/commands': [ 'wp', 'commands' ],
'@wordpress/components': [ 'wp', 'components' ],
'@wordpress/compose': [ 'wp', 'compose' ],
'@wordpress/core-data': [ 'wp', 'coreData' ],
'@wordpress/data': [ 'wp', 'data' ],
'@wordpress/data-controls': [ 'wp', 'dataControls' ],
'@wordpress/date': [ 'wp', 'date' ],
'@wordpress/dom': [ 'wp', 'dom' ],
'@wordpress/element': [ 'wp', 'element' ],
'@wordpress/html-entities': [ 'wp', 'htmlEntities' ],
'@wordpress/hooks': [ 'wp', 'hooks' ],
'@wordpress/i18n': [ 'wp', 'i18n' ],
'@wordpress/keyboard-shortcuts': [ 'wp', 'keyboardShortcuts' ],
'@wordpress/keycodes': [ 'wp', 'keycodes' ],
'@wordpress/notices': [ 'wp', 'notices' ],
'@wordpress/preferences': [ 'wp', 'preferences' ],
'@wordpress/primitives': [ 'wp', 'primitives' ],
'@wordpress/private-apis': [ 'wp', 'privateApis' ],
'@wordpress/url': [ 'wp', 'url' ],
'@wordpress/viewport': [ 'wp', 'viewport' ],
};
const SCRIPT_MODULE_EXTERNALS = {
'@wordpress/a11y': 'import @wordpress/a11y',
'@wordpress/boot': 'module @wordpress/boot',
'@wordpress/interactivity': 'module @wordpress/interactivity',
'@wordpress/interactivity-router': 'import @wordpress/interactivity-router',
'@wordpress/route': 'module @wordpress/route',
};
const BUNDLED_WORDPRESS_SCRIPT_MODULES = new Set( [
'@wordpress/dataviews',
'@wordpress/dataviews/wp',
'@wordpress/icons',
'@wordpress/views',
] );
const hasOwn = ( object, key ) => Object.prototype.hasOwnProperty.call( object, key );
const requestToExternalModule = ( request ) => {
if ( hasOwn( SCRIPT_MODULE_EXTERNALS, request ) ) {
return SCRIPT_MODULE_EXTERNALS[ request ];
}
if ( hasOwn( WORDPRESS_SCRIPT_GLOBALS, request ) || BUNDLED_WORDPRESS_SCRIPT_MODULES.has( request ) ) {
return false;
}
if ( request.startsWith( '@wordpress/' ) ) {
throw new Error(
`Unclassified WordPress module import "${ request }" in script-module build. Add it to SCRIPT_MODULE_EXTERNALS, WORDPRESS_SCRIPT_GLOBALS, or BUNDLED_WORDPRESS_SCRIPT_MODULES.`
);
}
return false;
};
const replaceModuleDependencyExtraction = ( plugins = [] ) => [
...plugins.filter( ( plugin ) => plugin.constructor.name !== 'DependencyExtractionWebpackPlugin' ),
new DependencyExtractionWebpackPlugin( {
requestToExternalModule,
useDefaults: false,
} ),
];
const wordpressScriptGlobalExternal = ( { request }, callback ) => {
if ( WORDPRESS_SCRIPT_GLOBALS[ request ] ) {
callback( null, WORDPRESS_SCRIPT_GLOBALS[ request ] );
return;
}
callback();
};
const getExternalEntries = ( externals ) => {
if ( Array.isArray( externals ) ) {
return externals;
}
return externals ? [ externals ] : [];
};
const withWordPressScriptGlobalExternals = ( externals ) => [
wordpressScriptGlobalExternal,
...getExternalEntries( externals ),
];
const getProjectSourceDirectory = ( modulePath = '' ) => {
if ( ! modulePath ) {
return null;
}
const relativePath = path.relative( PROJECT_SOURCE_DIR, modulePath );
if ( ! relativePath || relativePath.startsWith( '..' ) || path.isAbsolute( relativePath ) ) {
return null;
}
return relativePath.split( path.sep )[ 0 ];
};
const processConfig = ( config ) => {
const isModuleBuild = Boolean( config.output?.module );
const splitChunks = isModuleBuild
? config.optimization?.splitChunks
: {
...( config.optimization?.splitChunks || {} ),
cacheGroups: {
...( config.optimization?.splitChunks?.cacheGroups || {} ),
// App vendor chunk (other dependencies)
appVendors: {
test: /[\\/]node_modules[\\/]/,
name: 'app/vendors',
chunks: ( chunk ) => chunk.name && chunk.name.startsWith( 'app/' ),
priority: 20,
reuseExistingChunk: true,
enforce: true,
},
// Disable default vendors to avoid unused files
default: false,
defaultVendors: false,
},
};
const moduleRules = [
...( config.module?.rules || [] ),
{
test: /\.m?js$/,
resolve: {
fullySpecified: false,
},
},
...( isModuleBuild
? [
// Mark `@wordpress/views` side-effect-free so webpack can tree-shake
// its barrel export. Views' `useViewConfig` pulls in `lock-unlock.mjs`,
// which opts into `@wordpress/private-apis` under the name
// `@wordpress/views` — a name WordPress core's allowlist rejects,
// crashing the app at module-eval time. We only use `useView`, so
// letting webpack drop the unused chain avoids the crash.
{
test: /node_modules[\\/]@wordpress[\\/]views[\\/]/,
sideEffects: false,
},
]
: [] ),
];
return {
...config,
module: {
...config.module,
rules: moduleRules,
},
externalsType: isModuleBuild ? 'window' : config.externalsType,
externals: isModuleBuild ? withWordPressScriptGlobalExternals( config.externals ) : config.externals,
output: {
...config.output,
// Place JS chunks in their source directory with content hash for cache busting
chunkFilename: ( pathData ) => {
const chunk = pathData.chunk;
const chunkGraph = pathData.webpack?.chunkGraph;
if ( chunk && chunkGraph ) {
for ( const module of chunkGraph.getChunkModules( chunk ) ) {
const modulePath = module.resource || module.context || '';
const sourceDirectory = getProjectSourceDirectory( modulePath );
if ( sourceDirectory ) {
return `${ sourceDirectory }/[name].[contenthash:8].js`;
}
}
}
return '[name].[contenthash:8].js';
},
},
optimization: {
...config.optimization,
splitChunks,
},
plugins: isModuleBuild ? replaceModuleDependencyExtraction( config.plugins ) : config.plugins,
};
};
module.exports = Array.isArray( defaultConfig ) ? defaultConfig.map( processConfig ) : processConfig( defaultConfig );