-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathplugins.js
More file actions
184 lines (170 loc) · 5.61 KB
/
Copy pathplugins.js
File metadata and controls
184 lines (170 loc) · 5.61 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
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extraction-webpack-plugin');
const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const WebpackBar = require('webpackbar');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const { resolve } = require('path');
const RemoveEmptyScriptsPlugin = require('./plugins/remove-empty-scripts');
const CleanExtractedDeps = require('./plugins/clean-extracted-deps');
const TenUpToolkitTscPlugin = require('./plugins/tsc');
const {
hasStylelintConfig,
fromConfigRoot,
hasProjectFile,
maybeInsertStyleVersionHash,
} = require('../../utils');
const removeDistFolder = (file) => {
return file.replace(/(^\.\/dist\/)|^dist\//, '');
};
// There are differences between Windows and Posix when it comes to the WebpackBar
// This ensures that the same reporter is used everywhere
const webpackbarArguments =
process.env.JEST_WORKER_ID !== undefined ? { reporters: ['basic'] } : undefined;
module.exports = ({
isPackage,
isProduction,
projectConfig: {
devServer,
filenames,
devServerPort,
paths,
wpDependencyExternals,
analyze,
hot,
useBlockAssets,
},
packageConfig: { style },
buildFiles,
}) => {
const hasReactFastRefresh = hot && !isProduction;
const blocksSourceDirectory = resolve(process.cwd(), paths.blocksDir);
return [
devServer &&
new HtmlWebpackPlugin({
...(hasProjectFile('public/index.html') && { template: 'public/index.html' }),
}),
new ESLintPlugin({
failOnError: false,
fix: false,
lintDirtyModulesOnly: true,
}),
// MiniCSSExtractPlugin to extract the CSS that gets imported into JavaScript.
new MiniCSSExtractPlugin({
filename: (options) => {
if (isPackage) {
return removeDistFolder(style);
}
let entryModules = [];
try {
// with the react fast refresh plugin
// we cannot always assume there's a single entry module
// so we need to check if any of the entry modules are relative to blocksSourceDiretory
entryModules = options.chunk.getModules().filter((module) => {
return module.isEntryModule();
});
} catch (e) {
try {
// if it failed it's bc there's only one entryModule
entryModules.push(options.chunk.entryModule);
} catch (e) {
entryModules = [];
}
}
let isBlockAsset = entryModules.some((module) => {
const fullPath = module.resource;
return fullPath
? !path
.relative(blocksSourceDirectory, fullPath)
// startWith('../') but in a cross-env way
.startsWith(path.join('..', '/'))
: false;
});
if (!isBlockAsset) {
if (useBlockAssets) {
isBlockAsset =
// match windows and posix paths
buildFiles[options.chunk.name].match(/\/blocks?\//) ||
buildFiles[options.chunk.name].match(/\\blocks?\\/);
} else {
isBlockAsset = options.chunk.name.match(/-block$/);
}
}
return isBlockAsset ? filenames.blockCSS : filenames.css;
},
chunkFilename: '[id].css',
}),
!isPackage &&
// Copy static assets to the `dist` folder.
new CopyWebpackPlugin({
patterns: [
{
from: '**/*.{jpg,jpeg,png,gif,webp,avif,ico,svg,eot,ttf,woff,woff2,otf}',
to: '[path][name][ext]',
noErrorOnMissing: true,
context: path.resolve(process.cwd(), paths.copyAssetsDir),
},
useBlockAssets && {
from: path.join(blocksSourceDirectory, '**/block.json').replace(/\\/g, '/'),
context: blocksSourceDirectory,
noErrorOnMissing: true,
to: 'blocks/[path][name][ext]',
transform: (content, absoluteFilename) => {
return maybeInsertStyleVersionHash(content, absoluteFilename);
},
},
useBlockAssets && {
from: path.join(blocksSourceDirectory, '**/*.php').replace(/\\/g, '/'),
context: blocksSourceDirectory,
noErrorOnMissing: true,
to: 'blocks/[path][name][ext]',
},
hasReactFastRefresh && {
from: fromConfigRoot('fast-refresh.php'),
to: '[path][name][ext]',
noErrorOnMissing: true,
context: path.resolve(process.cwd(), '/dist'),
},
].filter(Boolean),
}),
// Lint CSS.
new StyleLintPlugin({
context: path.resolve(process.cwd(), paths.srcDir),
files: '**/*.(s(c|a)ss|css)',
allowEmptyInput: true,
lintDirtyModulesOnly: true,
failOnError: false,
...(!hasStylelintConfig() && {
configFile: fromConfigRoot('stylelint.config.js'),
}),
}),
// Fancy WebpackBar.
!hasReactFastRefresh && new WebpackBar(webpackbarArguments),
// dependencyExternals variable controls whether scripts' assets get
// generated, and the default externals set.
wpDependencyExternals &&
!isPackage &&
new DependencyExtractionWebpackPlugin({
injectPolyfill: false,
requestToHandle: (request) => {
if (request.includes('react-refresh/runtime')) {
return 'tenup-toolkit-react-refresh-runtime';
}
return undefined;
},
}),
new CleanExtractedDeps(),
new RemoveEmptyScriptsPlugin(),
new TenUpToolkitTscPlugin(),
analyze && isProduction && new BundleAnalyzerPlugin({ analyzerMode: 'static' }),
hasReactFastRefresh &&
new ReactRefreshWebpackPlugin({
overlay: { sockHost: '127.0.0.1', sockProtocol: 'ws', sockPort: devServerPort },
exclude: [/node_module/, /outputCssLoader\.js/],
}),
].filter(Boolean);
};