-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwebpack.config.js
More file actions
270 lines (251 loc) · 8.64 KB
/
Copy pathwebpack.config.js
File metadata and controls
270 lines (251 loc) · 8.64 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
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
/**
* This Webpack config augments the default wp-scripts "build" command with
* custom logic to properly process all of Shiro's existing code modules.
*
* It is focused on maintaining filename parity with the existing build where
* possible, while combining as many build processes into one Webpack command
* as we possibly can.
*/
/* eslint-disable import/no-extraneous-dependencies */// Used via wp-scripts.
const { dirname, resolve, basename } = require( 'path' );
const { globSync } = require( 'glob' );
const CopyPlugin = require( 'copy-webpack-plugin' );
const MiniCSSExtractPlugin = require( 'mini-css-extract-plugin' );
const RtlCssPlugin = require( '@wordpress/scripts/plugins/rtlcss-webpack-plugin' );
const { WebpackManifestPlugin } = require( 'webpack-manifest-plugin' );
// Import the original config from the @wordpress/scripts package.
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
// Import the helper to find and generate the entry points in the src directory
const { getWebpackEntryPoints } = require( '@wordpress/scripts/utils/config' );
const isProduction = process.env.NODE_ENV === 'production';
/**
* Generate an absolute file system path relative to the working dir.
*
* @param {string} relPath Relative path.
* @return {string} Absolute path.
*/
const filePath = ( relPath ) => resolve( process.cwd(), relPath );
/**
* Get a list of valid source files within the provided directory path.
*
* @param {string} globPath Project-relative glob path string.
* @return {string[]} Array of full file paths.
*/
const listFilesFrom = ( globPath ) => globSync( globPath )
// Limit to JS and CSS files.
.filter( ( relPath ) => /\.(jsx?|s?css)/.test( relPath) )
.map( ( relPath ) => resolve( process.cwd(), relPath ) );
// Build four different sets of entries, which get different filename treatment.
/** Set base path for block entries generated by wp-scripts helper. */
const blockEntries = getWebpackEntryPoints( 'script' )();
/** Bundles migrated from Shiro legacy Gulp build. */
const legacyEntries = {
datavis: listFilesFrom( 'assets/src/datavisjs/*' ),
// Render each shortcode to individual file.
...listFilesFrom( 'assets/src/shortcodejs/*' )
.reduce( ( entries, path ) => ( {
...entries,
[ basename( path ).replace( /\.(.*)$/, '' ) ]: path,
} ), {} ),
scripts: listFilesFrom( 'assets/src/js/**/*.js' ),
};
/** Bundles migrated from 1st-gen Shiro Webpack build. */
const hashedEntries = {
shiro: './assets/src/scripts/shiro.js',
};
const themeStylesheets = {
style: './assets/src/sass/style.scss',
'editor-style': './assets/src/sass/editor-style.scss',
};
/**
* Do not apply wp-scripts' naming strategy outside of block.json modules.
*
* Changing non-block style imports to `[group]-[chunkName]` (e.g. style-editor.css)
* is unnecessarily magic and breaks existing code.
*
* @param {Object} _ Module (unused).
* @param {Object[]} chunks Chunks array in this style group.
* @param {string} cacheGroupKey Group name.
* @return {string} Preferred chunk name.
*/
defaultConfig.optimization.splitChunks.cacheGroups.style.name = ( _, chunks, cacheGroupKey ) => {
const chunkName = chunks[ 0 ].name;
if ( /blocks\/[^\/]+\/index/.test( chunkName ) ) {
// Apply the wp-scripts processing where appropriate.
return `${ dirname(
chunkName
) }/${ cacheGroupKey }-${ basename( chunkName ) }`;
}
return chunkName;
};
// Do not process some url() imports in SCSS: The files are not located
// properly for relative import the way the css-loader expects, and it
// would slow down the build too much if they were.
// Iterate through rules until we find one that applies to SCSS, to avoid
// hard-coding WP config index specificity into our override.
defaultConfig.module.rules.forEach( ( rule ) => {
if ( ! rule.test.test( 'file.scss' ) ) {
return;
}
// We've isolated SCSS build.
rule.use.forEach( ( loader ) => {
if ( /\/sass-loader/.test( loader.loader ) ) {
// Turn off verbose and repetitive SASS deprecation warnings.
loader.options.sassOptions = {
...loader.options.sassOptions,
silenceDeprecations: [ 'import', 'mixed-decls' ],
};
}
if ( ! /\/css-loader/.test( loader.loader ) ) {
return;
}
// We've found the CSS loader itself. Options should be defined,
// but let's ensure it is, just in case.
loader.options = {
...loader.options,
url: {
/**
* Do not process url() statements for assets used in the legacy CSS files.
*
* @see https://webpack.js.org/loaders/css-loader/#url
*
* @param {string} url Path to asset referenced via url().
* @return {boolean} Whether to process with loader.
*/
filter( url ) {
return ! /assets\/(dist|src|fonts)/.test( url );
},
},
};
} );
} );
/**
* Map each entry to the correct filename format.
*
* (We upgraded the build process without wanting to completely re-wire the
* entire asset loading throughout the theme; this is the "comapat layer".)
*
* @param {PathData} pathData Webpack pathData object.
* @return {string} Filename string format.
*/
const setConditionalOutputFilename = ( { chunk } ) => {
if ( Object.keys( legacyEntries ).includes( chunk.name ) ) {
return '[name].min.js';
}
if ( Object.keys( hashedEntries ).includes( chunk.name ) ) {
return '[name]-[chunkhash].js';
}
// WP-Scripts default is to use asset.php for hash string, not filename.
return '[name].js';
};
/**
* Generate the CSS version of each contextually-appropriate output filename.
*
* @param {PathData} pathData Webpack pathData object.
* @return {string} Filename string format.
*/
const setExtractedCssFilename = ( pathData ) => {
return setConditionalOutputFilename( pathData ).replace( /\.js$/, '.css' );
};
// Extend webpack config to add entrypoints.
module.exports = {
...defaultConfig,
entry: {
...blockEntries,
...legacyEntries,
...hashedEntries,
...themeStylesheets,
editor: './assets/src/editor/index.js',
},
resolve: {
...defaultConfig.resolve,
alias: {
...defaultConfig.resolve.alias,
// Mapping for files used within migrated Webpack bundles.
'sass-lib': filePath( 'assets/src/sass' ),
},
},
output: {
...defaultConfig.output,
filename: setConditionalOutputFilename,
chunkFilename: '[name]-[contenthash].js',
// See https://webpack.js.org/migrate/5/#run-a-single-build-and-follow-advice
publicPath: '',
},
// Customize plugins to better control generated CSS filenames.
plugins: [
new WebpackManifestPlugin( {
fileName: `${ isProduction ? 'production' : 'development' }-asset-manifest.json`,
writeToFileEmit: true,
map: ( file ) => {
// Work around an issue https://github.com/romainberger/webpack-rtl-plugin/issues/14
// to make sure an RTL file has a separate entry in the manifest.
if ( ( /-rtl\.css$/ ).test( file.path ) ) {
file.name = file.name.replace( '.css', '-rtl.css' );
}
return file;
},
} ),
...defaultConfig.plugins.map( ( plugin ) => {
// Use our own versions of the MiniCSSExtract and RtlCSS plugins to
// control generation of output filenames more closely.
if ( plugin instanceof MiniCSSExtractPlugin ) {
return new MiniCSSExtractPlugin( {
filename: setExtractedCssFilename,
chunkFilename: setExtractedCssFilename,
} );
}
if ( plugin instanceof RtlCssPlugin ) {
return new RtlCssPlugin( {
filename: ( pathData ) => setExtractedCssFilename( pathData )
.replace( /\.css$/, '-rtl.css' ),
} );
}
return plugin;
} ),
new CopyPlugin( {
patterns: [
{
from: filePath( 'assets/src/fonts' ),
to: filePath( 'assets/dist/fonts' ),
},
{
from: filePath( 'assets/src/admin-copy' ),
to: filePath( 'assets/dist/admin' ),
},
{
from: filePath( 'assets/src/images' ),
to: filePath( 'assets/dist/images' ),
},
{
from: filePath( 'assets/src/libs' ),
to: filePath( 'assets/dist' ),
},
{
from: filePath( 'assets/src/svg/spritesheet' ),
to: filePath( 'assets/dist' ),
},
],
} ),
],
};
if (
process.env.WEBPACK_SERVE === 'true' &&
process.argv.includes( '--hot' )
) {
// Running in hot-reloading mode: customize the exported configuration
// to set a single runtime chunk (necessary for HMR to work across multiple
// block / theme bundles at once) and allow devServer access from all hosts.
// YOU MAY ALSO NEED TO INSTALL AND ACTIVATE THE GUTENBERG PLUGIN.
module.exports.devServer = {
...module.exports.devServer,
allowedHosts: 'all',
// Reload DevServer when non-built files change.
watchFiles: [ 'theme.json' ],
proxy: { '/assets/dist': { pathRewrite: { '^/assets/dist': '' } } }
};
module.exports.optimization = {
...module.exports.optimization,
runtimeChunk: 'single',
};
}