This repository has been archived by the owner on Aug 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebpack.config.js
110 lines (99 loc) · 2.45 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
/**
* External dependencies
*/
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const { join, sep } = require( 'path' );
const fastGlob = require( 'fast-glob' );
const postcss = require( 'postcss' );
/**
* WordPress dependencies
*/
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
/**
* Internal dependencies
*/
const { plugins } = require( './tools/shared' );
/**
* Escapes the RegExp special characters.
*
* @param {string} string Input string.
*
* @return {string} Regex-escaped string.
*/
function escapeRegExp( string ) {
return string.replace( /[\\^$.*+?()[\]{}|]/g, '\\$&' );
}
/*
* Matches a block's frontend JS filepaths.
*/
const blockViewRegex = new RegExp(
/block-library\/(?<filename>.*\/frontend.*).js$/
);
/*
* Creates the frontend script entrypoints.
*/
const createEntrypoints = () => {
const blockViewScriptPaths = fastGlob.sync(
'./src/block-library/**/frontend*.js'
);
return blockViewScriptPaths.reduce( ( entries, scriptPath ) => {
const result = scriptPath.match( blockViewRegex );
if ( ! result?.groups?.filename ) {
return entries;
}
return {
...entries,
[ result.groups.filename ]: scriptPath,
};
}, {} );
};
/**
* Uses PostCSS to transform css for development or production.
*
* @param {string} content The css content to modify.
*
* @return {string} The modified css content.
*/
const stylesTransform = ( content ) => {
return postcss( plugins )
.process( content, {
from: 'src/app.css',
to: 'dest/app.css',
} )
.then( ( result ) => result.css );
};
module.exports = {
...defaultConfig,
entry: Object.assign( defaultConfig.entry(), createEntrypoints() ),
output: {
filename: ( pathData ) => {
return pathData.chunk.name === 'index'
? '[name].js'
: 'block-library/[name].js';
},
path: defaultConfig?.output?.path,
},
plugins: [
...defaultConfig.plugins,
new CopyWebpackPlugin( {
patterns: Object.entries( {
'./src/block-library/': 'block-library',
'./src/template-library': 'template-library',
'./src/pattern-library': 'pattern-library',
} ).flatMap( ( [ from, to ] ) => [
{
from: `${ from }/**/block.css`,
to( { absoluteFilename } ) {
const [ , dirname ] = absoluteFilename.match(
new RegExp(
`([\\w-]+)${ escapeRegExp( sep ) }block\\.css$`
)
);
return join( to, dirname, 'block.css' );
},
transform: stylesTransform,
},
] ),
} ),
].filter( Boolean ),
};