@atomicsmash/cli 9.0.1-beta.3 → 10.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,230 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- const { existsSync, realpathSync, readFileSync } = require("fs");
4
- const path = require("path");
5
- const chalk = require("chalk");
6
- const { sync: glob } = require("fast-glob");
7
- const { sync: readPkgUp } = require("read-pkg-up");
8
- const { log } = console;
9
- const moduleFields = new Set(["viewScriptModule", "viewModule"]);
10
- const scriptFields = new Set(["viewScript", "script", "editorScript"]);
11
- const { packageJson, path: pkgPath } = readPkgUp({
12
- cwd: realpathSync(process.cwd()),
13
- });
14
- const getArgsFromCLI = (excludePrefixes) => {
15
- const args = process.argv.slice(2);
16
- if (excludePrefixes) {
17
- return args.filter((arg) => {
18
- return !excludePrefixes.some((prefix) => arg.startsWith(prefix));
19
- });
20
- }
21
- return args;
22
- };
23
- const getPackagePath = () => pkgPath;
24
- const hasPackageProp = (prop) =>
25
- // eslint-disable-next-line no-prototype-builtins
26
- packageJson && packageJson.hasOwnProperty(prop);
27
- const fromProjectRoot = (fileName) => path.join(path.dirname(getPackagePath()), fileName);
28
- const hasProjectFile = (fileName) => existsSync(fromProjectRoot(fileName));
29
- const fromConfigRoot = (fileName) => path.join(path.dirname(__dirname), "config", fileName);
30
- const hasBabelConfig = () => hasProjectFile(".babelrc.js") ||
31
- hasProjectFile(".babelrc.json") ||
32
- hasProjectFile("babel.config.js") ||
33
- hasProjectFile("babel.config.json") ||
34
- hasProjectFile(".babelrc") ||
35
- hasPackageProp("babel");
36
- const getArgFromCLI = (arg) => {
37
- for (const cliArg of getArgsFromCLI()) {
38
- const [name, value] = cliArg.split("=");
39
- if (name === arg) {
40
- return value || null;
41
- }
42
- }
43
- };
44
- const hasArgInCLI = (arg) => getArgFromCLI(arg) !== undefined;
45
- const hasCssnanoConfig = () => hasProjectFile(".cssnanorc") ||
46
- hasProjectFile(".cssnanorc.js") ||
47
- hasProjectFile(".cssnanorc.json") ||
48
- hasProjectFile(".cssnanorc.yaml") ||
49
- hasProjectFile(".cssnanorc.yml") ||
50
- hasProjectFile("cssnano.config.js") ||
51
- hasPackageProp("cssnano");
52
- const hasPostCSSConfig = () => hasProjectFile("postcss.config.js") ||
53
- hasProjectFile(".postcssrc") ||
54
- hasProjectFile(".postcssrc.json") ||
55
- hasProjectFile(".postcssrc.yaml") ||
56
- hasProjectFile(".postcssrc.yml") ||
57
- hasProjectFile(".postcssrc.js") ||
58
- hasPackageProp("postcss");
59
- function getWordPressSrcDirectory() {
60
- return process.env.WP_SRC_DIRECTORY || "src";
61
- }
62
- function getBlockJsonModuleFields(blockJson) {
63
- let result = null;
64
- for (const field of moduleFields) {
65
- if (Object.hasOwn(blockJson, field)) {
66
- if (!result) {
67
- result = {};
68
- }
69
- result[field] = blockJson[field];
70
- }
71
- }
72
- return result;
73
- }
74
- /**
75
- * @param {Object} blockJson
76
- * @return {null|Record<string, unknown>} Fields
77
- */
78
- function getBlockJsonScriptFields(blockJson) {
79
- let result = null;
80
- for (const field of scriptFields) {
81
- if (Object.hasOwn(blockJson, field)) {
82
- if (!result) {
83
- result = {};
84
- }
85
- result[field] = blockJson[field];
86
- }
87
- }
88
- return result;
89
- }
90
- function getWebpackEntryPoints(buildType) {
91
- /**
92
- * @return {Object<string,string>} The list of entry points.
93
- */
94
- return () => {
95
- // 1. Handles the legacy format for entry points when explicitly provided with the `process.env.WP_ENTRY`.
96
- if (process.env.WP_ENTRY) {
97
- return buildType === "script" ? JSON.parse(process.env.WP_ENTRY) : {};
98
- }
99
- // Continue only if the source directory exists.
100
- if (!hasProjectFile(getWordPressSrcDirectory())) {
101
- log(chalk.yellow(`Source directory "${getWordPressSrcDirectory()}" was not found. Please confirm there is a "src" directory in the root or the value passed to --webpack-src-dir is correct.`));
102
- return {};
103
- }
104
- // 2. Checks whether any block metadata files can be detected in the defined source directory.
105
- // It scans all discovered files looking for JavaScript assets and converts them to entry points.
106
- const blockMetadataFiles = glob("**/block.json", {
107
- absolute: true,
108
- cwd: fromProjectRoot(getWordPressSrcDirectory()),
109
- });
110
- if (blockMetadataFiles.length > 0) {
111
- const srcDirectory = fromProjectRoot(getWordPressSrcDirectory() + path.sep);
112
- const entryPoints = {};
113
- for (const blockMetadataFile of blockMetadataFiles) {
114
- const fileContents = readFileSync(blockMetadataFile);
115
- let parsedBlockJson;
116
- // wrapping in try/catch in case the file is malformed
117
- // this happens especially when new block.json files are added
118
- // at which point they are completely empty and therefore not valid JSON
119
- try {
120
- parsedBlockJson = JSON.parse(fileContents);
121
- }
122
- catch (error) {
123
- chalk.yellow(`Skipping "${blockMetadataFile.replace(fromProjectRoot(path.sep), "")}" due to malformed JSON.`);
124
- }
125
- const fields = buildType === "script"
126
- ? getBlockJsonScriptFields(parsedBlockJson)
127
- : getBlockJsonModuleFields(parsedBlockJson);
128
- if (!fields) {
129
- continue;
130
- }
131
- for (const value of Object.values(fields).flat()) {
132
- if (!value.startsWith("file:")) {
133
- continue;
134
- }
135
- // Removes the `file:` prefix.
136
- const filepath = path.join(path.dirname(blockMetadataFile), value.replace("file:", ""));
137
- // Takes the path without the file extension, and relative to the defined source directory.
138
- if (!filepath.startsWith(srcDirectory)) {
139
- log(chalk.yellow(`Skipping "${value.replace("file:", "")}" listed in "${blockMetadataFile.replace(fromProjectRoot(path.sep), "")}". File is located outside of the "${getWordPressSrcDirectory()}" directory.`));
140
- return;
141
- }
142
- const entryName = filepath
143
- .replace(path.extname(filepath), "")
144
- .replace(srcDirectory, "")
145
- .replace(/\\/g, "/");
146
- // Detects the proper file extension used in the defined source directory.
147
- const [entryFilepath] = glob(`${entryName}.?(m)[jt]s?(x)`, {
148
- absolute: true,
149
- cwd: fromProjectRoot(getWordPressSrcDirectory()),
150
- });
151
- if (!entryFilepath) {
152
- log(chalk.yellow(`Skipping "${value.replace("file:", "")}" listed in "${blockMetadataFile.replace(fromProjectRoot(path.sep), "")}". File does not exist in the "${getWordPressSrcDirectory()}" directory.`));
153
- return;
154
- }
155
- entryPoints[entryName] = entryFilepath;
156
- }
157
- }
158
- if (Object.keys(entryPoints).length > 0) {
159
- return entryPoints;
160
- }
161
- }
162
- // Don't do any further processing if this is a module build.
163
- // This only respects *module block.json fields.
164
- if (buildType === "module") {
165
- return {};
166
- }
167
- // 3. Checks whether a standard file name can be detected in the defined source directory,
168
- // and converts the discovered file to entry point.
169
- const [entryFile] = glob("index.[jt]s?(x)", {
170
- absolute: true,
171
- cwd: fromProjectRoot(getWordPressSrcDirectory()),
172
- });
173
- if (!entryFile) {
174
- log(chalk.yellow(`No entry file discovered in the "${getWordPressSrcDirectory()}" directory.`));
175
- return {};
176
- }
177
- return {
178
- index: entryFile,
179
- };
180
- };
181
- }
182
- function getPhpFilePaths(props) {
183
- // Continue only if the source directory exists.
184
- if (!hasProjectFile(getWordPressSrcDirectory())) {
185
- return [];
186
- }
187
- // Checks whether any block metadata files can be detected in the defined source directory.
188
- const blockMetadataFiles = glob("**/block.json", {
189
- absolute: true,
190
- cwd: fromProjectRoot(getWordPressSrcDirectory()),
191
- });
192
- const srcDirectory = fromProjectRoot(getWordPressSrcDirectory() + path.sep);
193
- return blockMetadataFiles.flatMap((blockMetadataFile) => {
194
- const blockJson = JSON.parse(readFileSync(blockMetadataFile));
195
- const paths = [];
196
- for (const prop of props) {
197
- if (typeof blockJson?.[prop] !== "string" ||
198
- !blockJson[prop]?.startsWith("file:")) {
199
- continue;
200
- }
201
- // Removes the `file:` prefix.
202
- const filepath = path.join(path.dirname(blockMetadataFile), blockJson[prop].replace("file:", ""));
203
- // Takes the path without the file extension, and relative to the defined source directory.
204
- if (!filepath.startsWith(srcDirectory)) {
205
- log(chalk.yellow(`Skipping "${blockJson[prop].replace("file:", "")}" listed in "${blockMetadataFile.replace(fromProjectRoot(path.sep), "")}". File is located outside of the "${getWordPressSrcDirectory()}" directory.`));
206
- continue;
207
- }
208
- paths.push(filepath.replace(/\\/g, "/"));
209
- }
210
- return paths;
211
- });
212
- }
213
- const getAsBooleanFromENV = (name) => {
214
- const value = process.env[name];
215
- return !!value && value !== "false" && value !== "0";
216
- };
217
- module.exports = {
218
- fromConfigRoot,
219
- hasBabelConfig,
220
- hasArgInCLI,
221
- hasCssnanoConfig,
222
- hasPostCSSConfig,
223
- getWordPressSrcDirectory,
224
- getWebpackEntryPoints,
225
- getPhpFilePaths,
226
- getAsBooleanFromENV,
227
- getBlockJsonModuleFields,
228
- getBlockJsonScriptFields,
229
- fromProjectRoot,
230
- };
@@ -1,19 +0,0 @@
1
- export function fromConfigRoot(fileName: any): string;
2
- export function hasBabelConfig(): any;
3
- export function hasArgInCLI(arg: any): boolean;
4
- export function hasCssnanoConfig(): any;
5
- export function hasPostCSSConfig(): any;
6
- export function getWordPressSrcDirectory(): string;
7
- export function getWebpackEntryPoints(buildType: any): () => {
8
- [x: string]: string;
9
- };
10
- export function getPhpFilePaths(props: any): string[];
11
- export function getAsBooleanFromENV(name: any): boolean;
12
- export function getBlockJsonModuleFields(blockJson: any): {} | null;
13
- /**
14
- * @param {Object} blockJson
15
- * @return {null|Record<string, unknown>} Fields
16
- */
17
- export function getBlockJsonScriptFields(blockJson: Object): null | Record<string, unknown>;
18
- export function fromProjectRoot(fileName: any): string;
19
- //# sourceMappingURL=utils.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/external/utils.cjs"],"names":[],"mappings":"AAoCA,sDACuD;AAEvD,sCAMwB;AAWxB,+CAA6D;AAE7D,wCAO0B;AAE1B,wCAO0B;AAC1B,mDAEC;AA8BD;;EAkJC;AACD,sDAmDC;AAED,wDAGC;AAxOD,oEAWC;AAED;;;GAGG;AACH,oDAHW,MAAM,GACL,IAAI,GAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAavC;AA3ED,uDACoD"}
@@ -1,438 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- /**
4
- * This file is an almost direct copy from wp-scripts. We have opted not to install
5
- * wp-scripts as it's hard to manage it's many dependencies against our other
6
- * workspaces.
7
- */
8
- // TODO: Merge in the relevant rules from this config to our own config directly.
9
- /**
10
- * External dependencies
11
- */
12
- const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
13
- const { CleanWebpackPlugin } = require("clean-webpack-plugin");
14
- const CopyWebpackPlugin = require("copy-webpack-plugin");
15
- const webpack = require("webpack");
16
- const browserslist = require("browserslist");
17
- const MiniCSSExtractPlugin = require("mini-css-extract-plugin");
18
- const { basename, dirname, resolve } = require("node:path");
19
- const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
20
- const RtlCssPlugin = require("rtlcss-webpack-plugin");
21
- const TerserPlugin = require("terser-webpack-plugin");
22
- const { realpathSync } = require("node:fs");
23
- const { sync: glob } = require("fast-glob");
24
- const { validate } = require("schema-utils");
25
- /**
26
- * WordPress dependencies
27
- */
28
- const DependencyExtractionWebpackPlugin = require("@wordpress/dependency-extraction-webpack-plugin");
29
- const postcssPlugins = require("@wordpress/postcss-plugins-preset");
30
- /**
31
- * Internal dependencies
32
- */
33
- const { fromConfigRoot, hasBabelConfig, hasArgInCLI, hasCssnanoConfig, hasPostCSSConfig, getWordPressSrcDirectory, getWebpackEntryPoints, getPhpFilePaths, getAsBooleanFromENV, getBlockJsonModuleFields, getBlockJsonScriptFields, fromProjectRoot, } = require("./utils.cjs");
34
- const isProduction = process.env.NODE_ENV === "production";
35
- const mode = isProduction ? "production" : "development";
36
- let target = "browserslist";
37
- if (!browserslist.findConfig(".")) {
38
- target += ":" + fromConfigRoot(".browserslistrc");
39
- }
40
- const hasReactFastRefresh = hasArgInCLI("--hot") && !isProduction;
41
- const hasExperimentalModulesFlag = getAsBooleanFromENV("WP_EXPERIMENTAL_MODULES");
42
- const phpFilePathsPluginSchema = {
43
- type: "object",
44
- properties: {
45
- props: {
46
- type: "array",
47
- items: {
48
- type: "string",
49
- },
50
- },
51
- },
52
- };
53
- /**
54
- * The plugin recomputes PHP file paths once on each compilation. It is necessary to avoid repeating processing
55
- * when filtering every discovered PHP file in the source folder. This is the most performant way to ensure that
56
- * changes in `block.json` files are picked up in watch mode.
57
- */
58
- class PhpFilePathsPlugin {
59
- /**
60
- * PHP file paths from `render` and `variations` props found in `block.json` files.
61
- *
62
- * @type {string[]}
63
- */
64
- static paths;
65
- constructor(options = {}) {
66
- validate(phpFilePathsPluginSchema, options, {
67
- name: "PHP File Paths Plugin",
68
- baseDataPath: "options",
69
- });
70
- this.options = options;
71
- }
72
- apply(compiler) {
73
- const pluginName = this.constructor.name;
74
- compiler.hooks.thisCompilation.tap(pluginName, () => {
75
- this.constructor.paths = getPhpFilePaths(this.options.props);
76
- });
77
- }
78
- }
79
- const cssLoaders = [
80
- {
81
- loader: MiniCSSExtractPlugin.loader,
82
- },
83
- {
84
- loader: require.resolve("css-loader"),
85
- options: {
86
- importLoaders: 1,
87
- sourceMap: !isProduction,
88
- modules: {
89
- auto: true,
90
- },
91
- },
92
- },
93
- {
94
- loader: require.resolve("postcss-loader"),
95
- options: {
96
- // Provide a fallback configuration if there's not
97
- // one explicitly available in the project.
98
- ...(!hasPostCSSConfig() && {
99
- postcssOptions: {
100
- ident: "postcss",
101
- sourceMap: !isProduction,
102
- plugins: isProduction
103
- ? [
104
- ...postcssPlugins,
105
- require("cssnano")({
106
- // Provide a fallback configuration if there's not
107
- // one explicitly available in the project.
108
- ...(!hasCssnanoConfig() && {
109
- preset: [
110
- "default",
111
- {
112
- discardComments: {
113
- removeAll: true,
114
- },
115
- },
116
- ],
117
- }),
118
- }),
119
- ]
120
- : postcssPlugins,
121
- },
122
- }),
123
- },
124
- },
125
- ];
126
- /** @type {webpack.Configuration} */
127
- const baseConfig = {
128
- mode,
129
- target,
130
- output: {
131
- filename: "[name].js",
132
- path: resolve(process.cwd(), "build"),
133
- },
134
- resolve: {
135
- alias: {
136
- "lodash-es": "lodash",
137
- },
138
- extensions: [".jsx", ".ts", ".tsx", "..."],
139
- },
140
- optimization: {
141
- // Only concatenate modules in production, when not analyzing bundles.
142
- concatenateModules: isProduction && !process.env.WP_BUNDLE_ANALYZER,
143
- splitChunks: {
144
- cacheGroups: {
145
- style: {
146
- type: "css/mini-extract",
147
- test: /[\\/]style(\.module)?\.(pc|sc|sa|c)ss$/,
148
- chunks: "all",
149
- enforce: true,
150
- name(_, chunks, cacheGroupKey) {
151
- const chunkName = chunks[0].name;
152
- return `${dirname(chunkName)}/${cacheGroupKey}-${basename(chunkName)}`;
153
- },
154
- },
155
- default: false,
156
- },
157
- },
158
- minimizer: [
159
- new TerserPlugin({
160
- parallel: true,
161
- terserOptions: {
162
- output: {
163
- comments: /translators:/i,
164
- },
165
- compress: {
166
- passes: 2,
167
- },
168
- mangle: {
169
- reserved: ["__", "_n", "_nx", "_x"],
170
- },
171
- },
172
- extractComments: false,
173
- }),
174
- ],
175
- },
176
- module: {
177
- rules: [
178
- {
179
- test: /\.m?(j|t)sx?$/,
180
- exclude: /node_modules/,
181
- use: [
182
- {
183
- loader: require.resolve("babel-loader"),
184
- options: {
185
- // Babel uses a directory within local node_modules
186
- // by default. Use the environment variable option
187
- // to enable more persistent caching.
188
- cacheDirectory: process.env.BABEL_CACHE_DIRECTORY || true,
189
- // Provide a fallback configuration if there's not
190
- // one explicitly available in the project.
191
- ...(!hasBabelConfig() && {
192
- babelrc: false,
193
- configFile: false,
194
- presets: [require.resolve("@wordpress/babel-preset-default")],
195
- plugins: [
196
- hasReactFastRefresh && require.resolve("react-refresh/babel"),
197
- ].filter(Boolean),
198
- }),
199
- },
200
- },
201
- ],
202
- },
203
- {
204
- test: /\.css$/,
205
- use: cssLoaders,
206
- },
207
- {
208
- test: /\.pcss$/,
209
- use: cssLoaders,
210
- },
211
- {
212
- test: /\.(sc|sa)ss$/,
213
- use: [
214
- ...cssLoaders,
215
- {
216
- loader: require.resolve("sass-loader"),
217
- options: {
218
- sourceMap: !isProduction,
219
- warnRuleAsWarning: false,
220
- implementation: require("sass"),
221
- api: "legacy",
222
- },
223
- },
224
- ],
225
- },
226
- {
227
- test: /\.svg$/,
228
- issuer: /\.(j|t)sx?$/,
229
- use: ["@svgr/webpack", "url-loader"],
230
- type: "javascript/auto",
231
- },
232
- {
233
- test: /\.svg$/,
234
- issuer: /\.(pc|sc|sa|c)ss$/,
235
- type: "asset/inline",
236
- },
237
- {
238
- test: /\.(bmp|png|jpe?g|gif|webp)$/i,
239
- type: "asset/resource",
240
- generator: {
241
- filename: "images/[name].[hash:8][ext]",
242
- },
243
- },
244
- {
245
- test: /\.(woff|woff2|eot|ttf|otf)$/i,
246
- type: "asset/resource",
247
- generator: {
248
- filename: "fonts/[name].[hash:8][ext]",
249
- },
250
- },
251
- ],
252
- },
253
- stats: {
254
- children: false,
255
- },
256
- };
257
- // WP_DEVTOOL global variable controls how source maps are generated.
258
- // See: https://webpack.js.org/configuration/devtool/#devtool.
259
- if (process.env.WP_DEVTOOL) {
260
- baseConfig.devtool = process.env.WP_DEVTOOL;
261
- }
262
- if (!isProduction) {
263
- // Set default sourcemap mode if it wasn't set by WP_DEVTOOL.
264
- baseConfig.devtool = baseConfig.devtool || "source-map";
265
- }
266
- // Add source-map-loader if devtool is set, whether in dev mode or not.
267
- if (baseConfig.devtool) {
268
- baseConfig.module.rules.unshift({
269
- test: /\.(j|t)sx?$/,
270
- exclude: [/node_modules/],
271
- use: require.resolve("source-map-loader"),
272
- enforce: "pre",
273
- });
274
- }
275
- /** @type {webpack.Configuration} */
276
- const scriptConfig = {
277
- ...baseConfig,
278
- entry: getWebpackEntryPoints("script"),
279
- devServer: isProduction
280
- ? undefined
281
- : {
282
- devMiddleware: {
283
- writeToDisk: true,
284
- },
285
- allowedHosts: "auto",
286
- host: "localhost",
287
- port: 8887,
288
- proxy: {
289
- "/build": {
290
- pathRewrite: {
291
- "^/build": "",
292
- },
293
- },
294
- },
295
- },
296
- plugins: [
297
- new webpack.DefinePlugin({
298
- // Inject the `SCRIPT_DEBUG` global, used for development features flagging.
299
- "globalThis.SCRIPT_DEBUG": JSON.stringify(!isProduction),
300
- SCRIPT_DEBUG: JSON.stringify(!isProduction),
301
- }),
302
- // If we run a modules build, the 2 compilations can "clean" each other's output
303
- // Prevent the cleaning from happening
304
- !hasExperimentalModulesFlag &&
305
- new CleanWebpackPlugin({
306
- cleanAfterEveryBuildPatterns: ["!fonts/**", "!images/**"],
307
- // Prevent it from deleting webpack assets during builds that have
308
- // multiple configurations returned in the webpack config.
309
- cleanStaleWebpackAssets: false,
310
- }),
311
- new PhpFilePathsPlugin({ props: ["render", "variations"] }),
312
- new CopyWebpackPlugin({
313
- patterns: [
314
- {
315
- from: "**/block.json",
316
- context: getWordPressSrcDirectory(),
317
- noErrorOnMissing: true,
318
- transform(content, absoluteFrom) {
319
- const convertExtension = (path) => {
320
- return path.replace(/\.m?(j|t)sx?$/, ".js");
321
- };
322
- if (basename(absoluteFrom) === "block.json") {
323
- const blockJson = JSON.parse(content.toString());
324
- [
325
- getBlockJsonScriptFields(blockJson),
326
- getBlockJsonModuleFields(blockJson),
327
- ].forEach((fields) => {
328
- if (fields) {
329
- for (const [key, value] of Object.entries(fields)) {
330
- if (Array.isArray(value)) {
331
- blockJson[key] = value.map(convertExtension);
332
- }
333
- else if (typeof value === "string") {
334
- blockJson[key] = convertExtension(value);
335
- }
336
- }
337
- }
338
- });
339
- return JSON.stringify(blockJson, null, 2);
340
- }
341
- return content;
342
- },
343
- },
344
- {
345
- from: "**/*.php",
346
- context: getWordPressSrcDirectory(),
347
- noErrorOnMissing: true,
348
- filter: (filepath) => {
349
- return (process.env.WP_COPY_PHP_FILES_TO_DIST ||
350
- PhpFilePathsPlugin.paths.includes(realpathSync(filepath).replace(/\\/g, "/")));
351
- },
352
- },
353
- ],
354
- }),
355
- // The WP_BUNDLE_ANALYZER global variable enables a utility that represents
356
- // bundle content as a convenient interactive zoomable treemap.
357
- process.env.WP_BUNDLE_ANALYZER && new BundleAnalyzerPlugin(),
358
- // MiniCSSExtractPlugin to extract the CSS thats gets imported into JavaScript.
359
- new MiniCSSExtractPlugin({ filename: "[name].css" }),
360
- // RtlCssPlugin to generate RTL CSS files.
361
- new RtlCssPlugin({
362
- filename: `[name]-rtl.css`,
363
- }),
364
- // React Fast Refresh.
365
- hasReactFastRefresh && new ReactRefreshWebpackPlugin(),
366
- // WP_NO_EXTERNALS global variable controls whether scripts' assets get
367
- // generated, and the default externals set.
368
- !process.env.WP_NO_EXTERNALS && new DependencyExtractionWebpackPlugin(),
369
- ].filter(Boolean),
370
- };
371
- if (hasExperimentalModulesFlag) {
372
- /**
373
- * Add block.json files to compilation to ensure changes trigger rebuilds when watching
374
- */
375
- class BlockJsonDependenciesPlugin {
376
- constructor() {
377
- /** @type {ReadonlyArray<string>} */
378
- this.blockJsonFiles = glob("**/block.json", {
379
- absolute: true,
380
- cwd: fromProjectRoot(getWordPressSrcDirectory()),
381
- });
382
- }
383
- /**
384
- * Apply the plugin
385
- * @param {webpack.Compiler} compiler the compiler instance
386
- * @return {void}
387
- */
388
- apply(compiler) {
389
- if (this.blockJsonFiles.length) {
390
- compiler.hooks.compilation.tap("BlockJsonDependenciesPlugin", (compilation) => {
391
- compilation.fileDependencies.addAll(this.blockJsonFiles);
392
- });
393
- }
394
- }
395
- }
396
- /** @type {webpack.Configuration} */
397
- const moduleConfig = {
398
- ...baseConfig,
399
- entry: getWebpackEntryPoints("module"),
400
- experiments: {
401
- ...baseConfig.experiments,
402
- outputModule: true,
403
- },
404
- output: {
405
- ...baseConfig.output,
406
- module: true,
407
- chunkFormat: "module",
408
- environment: {
409
- ...baseConfig.output.environment,
410
- module: true,
411
- },
412
- library: {
413
- ...baseConfig.output.library,
414
- type: "module",
415
- },
416
- },
417
- plugins: [
418
- new webpack.DefinePlugin({
419
- // Inject the `SCRIPT_DEBUG` global, used for development features flagging.
420
- "globalThis.SCRIPT_DEBUG": JSON.stringify(!isProduction),
421
- SCRIPT_DEBUG: JSON.stringify(!isProduction),
422
- }),
423
- // The WP_BUNDLE_ANALYZER global variable enables a utility that represents
424
- // bundle content as a convenient interactive zoomable treemap.
425
- process.env.WP_BUNDLE_ANALYZER && new BundleAnalyzerPlugin(),
426
- // MiniCSSExtractPlugin to extract the CSS thats gets imported into JavaScript.
427
- new MiniCSSExtractPlugin({ filename: "[name].css" }),
428
- // WP_NO_EXTERNALS global variable controls whether scripts' assets get
429
- // generated, and the default externals set.
430
- !process.env.WP_NO_EXTERNALS && new DependencyExtractionWebpackPlugin(),
431
- new BlockJsonDependenciesPlugin(),
432
- ].filter(Boolean),
433
- };
434
- module.exports = [scriptConfig, moduleConfig];
435
- }
436
- else {
437
- module.exports = scriptConfig;
438
- }