@storybook/preset-create-react-app 9.2.0-alpha.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.
package/README.md CHANGED
@@ -117,7 +117,7 @@ config directory. If you have changed the conditions to utilize an `exclude`, th
117
117
  be true (which isn't likely going to work as expected).
118
118
 
119
119
  The steps to remedy this would be to follow the steps for customizing the webpack config within the storybook
120
- side of things. [Details for storybook custom webpack config](https://storybook.js.org/docs/configurations/custom-webpack-config/)
120
+ side of things. [Details for storybook custom webpack config](https://storybook.js.org/docs/configurations/custom-webpack-config/?ref=readme)
121
121
  You'll have access to all of the rules in `config.module.rules`. You'll need to find the offending rule,
122
122
  and customize it how you need it to be to be compatible with your fork.
123
123
 
@@ -128,3 +128,5 @@ concerning the conditions.
128
128
 
129
129
  - [Walkthrough to set up Storybook Docs with CRA & typescript](https://gist.github.com/shilman/bc9cbedb2a7efb5ec6710337cbd20c0c)
130
130
  - [Example projects (used for testing this preset)](https://github.com/storybookjs/presets/tree/master/examples)
131
+
132
+ Learn more about Storybook at [storybook.js.org](https://storybook.js.org/?ref=readme).
package/dist/index.js CHANGED
@@ -1 +1,463 @@
1
- "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var index_exports={};__export(index_exports,{core:()=>exportedCore,webpack:()=>exportedWebpack});module.exports=__toCommonJS(index_exports);var import_node_path4=require("path"),import_node_logger2=require("storybook/internal/node-logger"),import_pnp_webpack_plugin=__toESM(require("pnp-webpack-plugin"));var import_node_logger=require("storybook/internal/node-logger"),incompatiblePresets=["@storybook/preset-scss","@storybook/preset-typescript"],checkPresets=options=>{let{presetsList}=options;presetsList?.forEach(preset=>{let presetName=typeof preset=="string"?preset:preset.name;incompatiblePresets.includes(presetName)&&import_node_logger.logger.warn(`\`${presetName}\` may not be compatible with \`@storybook/preset-create-react-app\``)})};var import_node_fs=require("fs"),import_node_path=require("path"),JSCONFIG="jsconfig.json",TSCONFIG="tsconfig.json",getModulePath=appDirectory=>{let configName="";(0,import_node_fs.existsSync)((0,import_node_path.join)(appDirectory,TSCONFIG))?configName=TSCONFIG:(0,import_node_fs.existsSync)((0,import_node_path.join)(appDirectory,JSCONFIG))&&(configName=JSCONFIG);try{let{baseUrl}=require((0,import_node_path.join)(appDirectory,configName)).compilerOptions;return baseUrl?[baseUrl]:[]}catch{return[]}};var import_node_fs2=require("fs"),import_node_path2=require("path"),getReactScriptsPath=()=>{let cwd=process.cwd(),scriptsBinPath=(0,import_node_path2.join)(cwd,"/node_modules/.bin/react-scripts");if(process.platform==="win32")try{let packagePathMatch=(0,import_node_fs2.readFileSync)(scriptsBinPath,"utf8").match(/"\$basedir[\\/](\S+?)[\\/]bin[\\/]react-scripts\.js"/i);if(packagePathMatch&&packagePathMatch.length>1)return(0,import_node_path2.join)(cwd,"/node_modules/.bin/",packagePathMatch[1])}catch{}else try{let scriptsBinPathStat=(0,import_node_fs2.lstatSync)(scriptsBinPath);if(scriptsBinPathStat.isSymbolicLink()===!0){let resolvedBinPath=(0,import_node_fs2.realpathSync)(scriptsBinPath);return(0,import_node_path2.join)(resolvedBinPath,"..","..")}if(scriptsBinPathStat.isFile()===!0)return(0,import_node_path2.join)(cwd,"/node_modules/react-scripts")}catch{}try{return(0,import_node_path2.dirname)(require.resolve("react-scripts/package.json"))}catch{}return""};var import_react_refresh_webpack_plugin=__toESM(require("@pmmmwh/react-refresh-webpack-plugin")),mergePlugins=(...args)=>args?.reduce((plugins,plugin)=>{if(plugins?.some(includedPlugin=>includedPlugin?.constructor.name===plugin?.constructor.name)||plugin?.constructor.name==="WebpackManifestPlugin")return plugins;let updatedPlugin=plugin;return plugin?.constructor.name==="ReactRefreshPlugin"&&(updatedPlugin=new import_react_refresh_webpack_plugin.default({overlay:{sockIntegration:"whm"}})),[...plugins??[],updatedPlugin]},[]);var import_node_path3=require("path"),import_semver=__toESM(require("semver")),isRegExp=value=>value instanceof RegExp,isString=value=>typeof value=="string",testMatch=(rule,string)=>rule.test?Array.isArray(rule.test)?rule.test.some(test=>isRegExp(test)&&test.test(string)):isRegExp(rule.test)&&rule.test.test(string):!1,processCraConfig=async(craWebpackConfig,options)=>{let configDir=(0,import_node_path3.resolve)(options.configDir),storybookVersion=import_semver.default.coerce(options.packageJson?.version)||"",isStorybook530=import_semver.default.gte(storybookVersion,"5.3.0"),babelOptions=await options.presets.apply("babel");return craWebpackConfig?.module?.rules?craWebpackConfig.module.rules.reduce((rules,rule)=>{let{oneOf,include}=rule;if(testMatch(rule,".jsx")){let newRule={...rule,include:[include,configDir].filter(Boolean)};return[...rules,newRule]}return oneOf?[...rules,{oneOf:oneOf.map(oneOfRule=>{if(oneOfRule.type==="asset/resource"){if(isStorybook530){let excludes=["ejs","md","mdx","cjs",...options.craOverrides?.fileLoaderExcludes||[]],excludeRegex=new RegExp(`\\.(${excludes.join("|")})$`);return{...oneOfRule,exclude:[...oneOfRule.exclude,excludeRegex]}}return{}}if(testMatch(oneOfRule,".css"))return{...oneOfRule,include:isStorybook530?void 0:[configDir],exclude:[oneOfRule.exclude,/@storybook/]};let isBabelLoader=isString(oneOfRule.loader)&&/[/\\]babel-loader[/\\]/.test(oneOfRule.loader);if(isBabelLoader&&isRegExp(oneOfRule.test)&&oneOfRule.test.test(".jsx")){let{include:_include,options:ruleOptions}=oneOfRule,{plugins:rulePlugins,presets:rulePresets,overrides:ruleOverrides}=typeof ruleOptions=="object"?ruleOptions:{},{extends:_extends,plugins,presets,overrides}=babelOptions;return{...oneOfRule,include:[_include,configDir].filter(Boolean),options:{...ruleOptions,extends:_extends,plugins:[...plugins??[],...rulePlugins??[]],presets:[...presets??[],...rulePresets??[]],overrides:[...overrides??[],...ruleOverrides??[]]}}}return isBabelLoader&&isRegExp(oneOfRule.test)&&oneOfRule.test.test(".js")?{...oneOfRule,include:[configDir]}:oneOfRule})}]:[...rules,rule]},[]):[]};var CWD=process.cwd(),REACT_SCRIPTS_PATH=getReactScriptsPath(),OPTION_SCRIPTS_PACKAGE="scriptsPackageName";process.env.PUBLIC_URL||(process.env.PUBLIC_URL=".");var resolveLoader={modules:["node_modules",(0,import_node_path4.join)(REACT_SCRIPTS_PATH,"node_modules")],plugins:[import_pnp_webpack_plugin.default.moduleLoader(module)]},core=existing=>({...existing,disableWebpackDefaults:!0}),webpack=async(webpackConfig={},options)=>{let scriptsPath=REACT_SCRIPTS_PATH;checkPresets(options);let scriptsPackageName=options[OPTION_SCRIPTS_PACKAGE];if(typeof scriptsPackageName=="string")try{scriptsPath=(0,import_node_path4.dirname)(require.resolve(`${scriptsPackageName}/package.json`,{paths:[options.configDir]}))}catch{import_node_logger2.logger.warn(`A \`${OPTION_SCRIPTS_PACKAGE}\` was provided, but couldn't be resolved.`)}if(!scriptsPath)return import_node_logger2.logger.error("Failed to resolve a `react-scripts` package."),webpackConfig;import_node_logger2.logger.info(`=> Loading Webpack configuration from \`${(0,import_node_path4.relative)(CWD,scriptsPath)}\``),import_node_logger2.logger.info("=> Removing existing JavaScript and TypeScript rules.");let filteredRules=webpackConfig.module?.rules?.filter(rule=>{if(typeof rule=="string")return!1;let{test}=rule;return!(test instanceof RegExp&&(test?.test(".js")||test?.test(".ts")))}),craWebpackConfigPath=(0,import_node_path4.join)(scriptsPath,"config","webpack.config"),craWebpackConfig=require(craWebpackConfigPath)(webpackConfig.mode);import_node_logger2.logger.info("=> Modifying Create React App rules.");let craRules=await processCraConfig(craWebpackConfig,options),isProd=webpackConfig.mode!=="development",builder=(await options.presets.apply("core"))?.builder,builderOptions=typeof builder=="string"?{}:builder?.options,cacheConfig=builderOptions?.fsCache?{cache:{type:"filesystem"}}:{},lazyCompilationConfig=builderOptions?.lazyCompilation&&!isProd?{experiments:{lazyCompilation:{entries:!1}}}:{};return{...webpackConfig,...cacheConfig,...lazyCompilationConfig,module:{...webpackConfig.module,rules:[...filteredRules||[],...craRules]},plugins:mergePlugins(...webpackConfig.plugins??[],...craWebpackConfig.plugins??[]),resolve:{...webpackConfig.resolve,extensions:craWebpackConfig.resolve?.extensions,modules:[...webpackConfig.resolve&&webpackConfig.resolve.modules||[],(0,import_node_path4.join)(REACT_SCRIPTS_PATH,"node_modules"),...getModulePath(CWD)],plugins:[import_pnp_webpack_plugin.default],conditionNames:[...webpackConfig.resolve?.conditionNames??[],"storybook","stories","test","..."]},resolveLoader}},exportedCore=core,exportedWebpack=webpack;0&&(module.exports={core,webpack});
1
+ import CJS_COMPAT_NODE_URL_kr5t3c78h3 from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_kr5t3c78h3 from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_kr5t3c78h3 from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_kr5t3c78h3.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_kr5t3c78h3.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_kr5t3c78h3.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+ var __defProp = Object.defineProperty;
13
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
15
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
16
+ }) : x)(function(x) {
17
+ if (typeof require !== "undefined") return require.apply(this, arguments);
18
+ throw Error('Dynamic require of "' + x + '" is not supported');
19
+ });
20
+
21
+ // src/index.ts
22
+ import { dirname as dirname2, join as join4, relative as relative2 } from "node:path";
23
+ import { logger as logger2 } from "storybook/internal/node-logger";
24
+ import PnpWebpackPlugin from "pnp-webpack-plugin";
25
+
26
+ // src/helpers/checkPresets.ts
27
+ import { logger } from "storybook/internal/node-logger";
28
+ var incompatiblePresets = ["@storybook/preset-scss", "@storybook/preset-typescript"];
29
+ var checkPresets = /* @__PURE__ */ __name((options) => {
30
+ const { presetsList } = options;
31
+ presetsList?.forEach((preset) => {
32
+ const presetName = typeof preset === "string" ? preset : preset.name;
33
+ if (incompatiblePresets.includes(presetName)) {
34
+ logger.warn(
35
+ `\`${presetName}\` may not be compatible with \`@storybook/preset-create-react-app\``
36
+ );
37
+ }
38
+ });
39
+ }, "checkPresets");
40
+
41
+ // src/helpers/getModulePath.ts
42
+ import { existsSync } from "node:fs";
43
+ import { join } from "node:path";
44
+ var JSCONFIG = "jsconfig.json";
45
+ var TSCONFIG = "tsconfig.json";
46
+ var getModulePath = /* @__PURE__ */ __name((appDirectory) => {
47
+ let configName = "";
48
+ if (existsSync(join(appDirectory, TSCONFIG))) {
49
+ configName = TSCONFIG;
50
+ } else if (existsSync(join(appDirectory, JSCONFIG))) {
51
+ configName = JSCONFIG;
52
+ }
53
+ try {
54
+ const { baseUrl } = __require(join(appDirectory, configName)).compilerOptions;
55
+ return baseUrl ? [baseUrl] : [];
56
+ } catch (e) {
57
+ return [];
58
+ }
59
+ }, "getModulePath");
60
+
61
+ // src/helpers/getReactScriptsPath.ts
62
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
63
+ import { join as join3 } from "node:path";
64
+
65
+ // ../../core/src/shared/utils/module.ts
66
+ import { fileURLToPath, pathToFileURL } from "node:url";
67
+
68
+ // ../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
69
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
70
+ function normalizeWindowsPath(input = "") {
71
+ if (!input) {
72
+ return input;
73
+ }
74
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
75
+ }
76
+ __name(normalizeWindowsPath, "normalizeWindowsPath");
77
+ var _UNC_REGEX = /^[/\\]{2}/;
78
+ var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
79
+ var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
80
+ var normalize = /* @__PURE__ */ __name(function(path2) {
81
+ if (path2.length === 0) {
82
+ return ".";
83
+ }
84
+ path2 = normalizeWindowsPath(path2);
85
+ const isUNCPath = path2.match(_UNC_REGEX);
86
+ const isPathAbsolute = isAbsolute(path2);
87
+ const trailingSeparator = path2[path2.length - 1] === "/";
88
+ path2 = normalizeString(path2, !isPathAbsolute);
89
+ if (path2.length === 0) {
90
+ if (isPathAbsolute) {
91
+ return "/";
92
+ }
93
+ return trailingSeparator ? "./" : ".";
94
+ }
95
+ if (trailingSeparator) {
96
+ path2 += "/";
97
+ }
98
+ if (_DRIVE_LETTER_RE.test(path2)) {
99
+ path2 += "/";
100
+ }
101
+ if (isUNCPath) {
102
+ if (!isPathAbsolute) {
103
+ return `//./${path2}`;
104
+ }
105
+ return `//${path2}`;
106
+ }
107
+ return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
108
+ }, "normalize");
109
+ var join2 = /* @__PURE__ */ __name(function(...arguments_) {
110
+ if (arguments_.length === 0) {
111
+ return ".";
112
+ }
113
+ let joined;
114
+ for (const argument of arguments_) {
115
+ if (argument && argument.length > 0) {
116
+ if (joined === void 0) {
117
+ joined = argument;
118
+ } else {
119
+ joined += `/${argument}`;
120
+ }
121
+ }
122
+ }
123
+ if (joined === void 0) {
124
+ return ".";
125
+ }
126
+ return normalize(joined.replace(/\/\/+/g, "/"));
127
+ }, "join");
128
+ function normalizeString(path2, allowAboveRoot) {
129
+ let res = "";
130
+ let lastSegmentLength = 0;
131
+ let lastSlash = -1;
132
+ let dots = 0;
133
+ let char = null;
134
+ for (let index = 0; index <= path2.length; ++index) {
135
+ if (index < path2.length) {
136
+ char = path2[index];
137
+ } else if (char === "/") {
138
+ break;
139
+ } else {
140
+ char = "/";
141
+ }
142
+ if (char === "/") {
143
+ if (lastSlash === index - 1 || dots === 1) ;
144
+ else if (dots === 2) {
145
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
146
+ if (res.length > 2) {
147
+ const lastSlashIndex = res.lastIndexOf("/");
148
+ if (lastSlashIndex === -1) {
149
+ res = "";
150
+ lastSegmentLength = 0;
151
+ } else {
152
+ res = res.slice(0, lastSlashIndex);
153
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
154
+ }
155
+ lastSlash = index;
156
+ dots = 0;
157
+ continue;
158
+ } else if (res.length > 0) {
159
+ res = "";
160
+ lastSegmentLength = 0;
161
+ lastSlash = index;
162
+ dots = 0;
163
+ continue;
164
+ }
165
+ }
166
+ if (allowAboveRoot) {
167
+ res += res.length > 0 ? "/.." : "..";
168
+ lastSegmentLength = 2;
169
+ }
170
+ } else {
171
+ if (res.length > 0) {
172
+ res += `/${path2.slice(lastSlash + 1, index)}`;
173
+ } else {
174
+ res = path2.slice(lastSlash + 1, index);
175
+ }
176
+ lastSegmentLength = index - lastSlash - 1;
177
+ }
178
+ lastSlash = index;
179
+ dots = 0;
180
+ } else if (char === "." && dots !== -1) {
181
+ ++dots;
182
+ } else {
183
+ dots = -1;
184
+ }
185
+ }
186
+ return res;
187
+ }
188
+ __name(normalizeString, "normalizeString");
189
+ var isAbsolute = /* @__PURE__ */ __name(function(p) {
190
+ return _IS_ABSOLUTE_RE.test(p);
191
+ }, "isAbsolute");
192
+ var dirname = /* @__PURE__ */ __name(function(p) {
193
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
194
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
195
+ segments[0] += "/";
196
+ }
197
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
198
+ }, "dirname");
199
+
200
+ // ../../core/src/shared/utils/module.ts
201
+ var importMetaResolve = /* @__PURE__ */ __name((...args) => {
202
+ if (typeof import.meta.resolve !== "function" && process.env.VITEST === "true") {
203
+ console.warn(
204
+ "importMetaResolve from within Storybook is being used in a Vitest test, but it shouldn't be. Please report this at https://github.com/storybookjs/storybook/issues/new?template=bug_report.yml"
205
+ );
206
+ return pathToFileURL(args[0]).href;
207
+ }
208
+ return import.meta.resolve(...args);
209
+ }, "importMetaResolve");
210
+ var resolvePackageDir = /* @__PURE__ */ __name((pkg, parent) => {
211
+ return dirname(fileURLToPath(importMetaResolve(join2(pkg, "package.json"), parent)));
212
+ }, "resolvePackageDir");
213
+
214
+ // src/helpers/getReactScriptsPath.ts
215
+ var getReactScriptsPath = /* @__PURE__ */ __name(() => {
216
+ const cwd = process.cwd();
217
+ const scriptsBinPath = join3(cwd, "/node_modules/.bin/react-scripts");
218
+ if (process.platform === "win32") {
219
+ try {
220
+ const content = readFileSync(scriptsBinPath, "utf8");
221
+ const packagePathMatch = content.match(
222
+ /"\$basedir[\\/](\S+?)[\\/]bin[\\/]react-scripts\.js"/i
223
+ );
224
+ if (packagePathMatch && packagePathMatch.length > 1) {
225
+ const scriptsPath = join3(cwd, "/node_modules/.bin/", packagePathMatch[1]);
226
+ return scriptsPath;
227
+ }
228
+ } catch (e) {
229
+ }
230
+ } else {
231
+ try {
232
+ const scriptsBinPathStat = lstatSync(scriptsBinPath);
233
+ if (scriptsBinPathStat.isSymbolicLink() === true) {
234
+ const resolvedBinPath = realpathSync(scriptsBinPath);
235
+ const scriptsPath = join3(resolvedBinPath, "..", "..");
236
+ return scriptsPath;
237
+ }
238
+ if (scriptsBinPathStat.isFile() === true) {
239
+ const scriptsPath = join3(cwd, "/node_modules/react-scripts");
240
+ return scriptsPath;
241
+ }
242
+ } catch (e) {
243
+ }
244
+ }
245
+ try {
246
+ const scriptsPath = resolvePackageDir("react-scripts");
247
+ return scriptsPath;
248
+ } catch (e) {
249
+ }
250
+ return "";
251
+ }, "getReactScriptsPath");
252
+
253
+ // src/helpers/mergePlugins.ts
254
+ import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin";
255
+ var mergePlugins = /* @__PURE__ */ __name((...args) => args?.reduce((plugins, plugin) => {
256
+ if (plugins?.some(
257
+ (includedPlugin) => includedPlugin?.constructor.name === plugin?.constructor.name
258
+ ) || plugin?.constructor.name === "WebpackManifestPlugin") {
259
+ return plugins;
260
+ }
261
+ let updatedPlugin = plugin;
262
+ if (plugin?.constructor.name === "ReactRefreshPlugin") {
263
+ updatedPlugin = new ReactRefreshWebpackPlugin({
264
+ overlay: {
265
+ sockIntegration: "whm"
266
+ }
267
+ });
268
+ }
269
+ return [...plugins ?? [], updatedPlugin];
270
+ }, []), "mergePlugins");
271
+
272
+ // src/helpers/processCraConfig.ts
273
+ import { resolve as resolve2 } from "node:path";
274
+ import semver from "semver";
275
+ var isRegExp = /* @__PURE__ */ __name((value) => value instanceof RegExp, "isRegExp");
276
+ var isString = /* @__PURE__ */ __name((value) => typeof value === "string", "isString");
277
+ var testMatch = /* @__PURE__ */ __name((rule, string) => {
278
+ if (!rule.test) {
279
+ return false;
280
+ }
281
+ return Array.isArray(rule.test) ? rule.test.some((test) => isRegExp(test) && test.test(string)) : isRegExp(rule.test) && rule.test.test(string);
282
+ }, "testMatch");
283
+ var processCraConfig = /* @__PURE__ */ __name(async (craWebpackConfig, options) => {
284
+ const configDir = resolve2(options.configDir);
285
+ const storybookVersion = semver.coerce(options.packageJson?.version) || "";
286
+ const isStorybook530 = semver.gte(storybookVersion, "5.3.0");
287
+ const babelOptions = await options.presets.apply("babel");
288
+ if (!craWebpackConfig?.module?.rules) {
289
+ return [];
290
+ }
291
+ return craWebpackConfig.module.rules.reduce((rules, rule) => {
292
+ const { oneOf, include } = rule;
293
+ if (testMatch(rule, ".jsx")) {
294
+ const newRule = {
295
+ ...rule,
296
+ include: [include, configDir].filter(Boolean)
297
+ };
298
+ return [...rules, newRule];
299
+ }
300
+ if (oneOf) {
301
+ return [
302
+ ...rules,
303
+ {
304
+ // @ts-expect-error (broken typings from webpack)
305
+ oneOf: oneOf.map((oneOfRule) => {
306
+ if (oneOfRule.type === "asset/resource") {
307
+ if (isStorybook530) {
308
+ const excludes = [
309
+ "ejs",
310
+ // Used within Storybook.
311
+ "md",
312
+ // Used with Storybook Notes.
313
+ "mdx",
314
+ // Used with Storybook Docs.
315
+ "cjs",
316
+ // Used for CommonJS modules.
317
+ ...options.craOverrides?.fileLoaderExcludes || []
318
+ ];
319
+ const excludeRegex = new RegExp(`\\.(${excludes.join("|")})$`);
320
+ return {
321
+ ...oneOfRule,
322
+ exclude: [...oneOfRule.exclude, excludeRegex]
323
+ };
324
+ }
325
+ return {};
326
+ }
327
+ if (testMatch(oneOfRule, ".css")) {
328
+ return {
329
+ ...oneOfRule,
330
+ include: isStorybook530 ? void 0 : [configDir],
331
+ exclude: [oneOfRule.exclude, /@storybook/]
332
+ };
333
+ }
334
+ const isBabelLoader = isString(oneOfRule.loader) && /[/\\]babel-loader[/\\]/.test(oneOfRule.loader);
335
+ if (isBabelLoader && isRegExp(oneOfRule.test) && oneOfRule.test.test(".jsx")) {
336
+ const { include: _include, options: ruleOptions } = oneOfRule;
337
+ const {
338
+ plugins: rulePlugins,
339
+ presets: rulePresets,
340
+ overrides: ruleOverrides
341
+ } = typeof ruleOptions === "object" ? ruleOptions : {};
342
+ const { extends: _extends, plugins, presets, overrides } = babelOptions;
343
+ return {
344
+ ...oneOfRule,
345
+ include: [_include, configDir].filter(Boolean),
346
+ options: {
347
+ ...ruleOptions,
348
+ extends: _extends,
349
+ plugins: [...plugins ?? [], ...rulePlugins ?? []],
350
+ presets: [...presets ?? [], ...rulePresets ?? []],
351
+ overrides: [...overrides ?? [], ...ruleOverrides ?? []]
352
+ }
353
+ };
354
+ }
355
+ if (isBabelLoader && isRegExp(oneOfRule.test) && oneOfRule.test.test(".js")) {
356
+ return {
357
+ ...oneOfRule,
358
+ include: [configDir]
359
+ };
360
+ }
361
+ return oneOfRule;
362
+ })
363
+ }
364
+ ];
365
+ }
366
+ return [...rules, rule];
367
+ }, []);
368
+ }, "processCraConfig");
369
+
370
+ // src/index.ts
371
+ var CWD = process.cwd();
372
+ var REACT_SCRIPTS_PATH = getReactScriptsPath();
373
+ var OPTION_SCRIPTS_PACKAGE = "scriptsPackageName";
374
+ if (!process.env.PUBLIC_URL) {
375
+ process.env.PUBLIC_URL = ".";
376
+ }
377
+ var resolveLoader = {
378
+ modules: ["node_modules", join4(REACT_SCRIPTS_PATH, "node_modules")],
379
+ plugins: [PnpWebpackPlugin.moduleLoader(module)]
380
+ };
381
+ var core = /* @__PURE__ */ __name((existing) => ({
382
+ ...existing,
383
+ disableWebpackDefaults: true
384
+ }), "core");
385
+ var webpack = /* @__PURE__ */ __name(async (webpackConfig = {}, options) => {
386
+ let scriptsPath = REACT_SCRIPTS_PATH;
387
+ checkPresets(options);
388
+ const scriptsPackageName = options[OPTION_SCRIPTS_PACKAGE];
389
+ if (typeof scriptsPackageName === "string") {
390
+ try {
391
+ scriptsPath = dirname2(
392
+ __require.resolve(`${scriptsPackageName}/package.json`, {
393
+ paths: [options.configDir]
394
+ })
395
+ );
396
+ } catch (e) {
397
+ logger2.warn(`A \`${OPTION_SCRIPTS_PACKAGE}\` was provided, but couldn't be resolved.`);
398
+ }
399
+ }
400
+ if (!scriptsPath) {
401
+ logger2.error("Failed to resolve a `react-scripts` package.");
402
+ return webpackConfig;
403
+ }
404
+ logger2.info(`=> Loading Webpack configuration from \`${relative2(CWD, scriptsPath)}\``);
405
+ logger2.info(`=> Removing existing JavaScript and TypeScript rules.`);
406
+ const filteredRules = webpackConfig.module?.rules?.filter((rule) => {
407
+ if (typeof rule === "string") {
408
+ return false;
409
+ }
410
+ const { test } = rule;
411
+ return !(test instanceof RegExp && (test?.test(".js") || test?.test(".ts")));
412
+ });
413
+ const craWebpackConfigPath = join4(scriptsPath, "config", "webpack.config");
414
+ const craWebpackConfig = __require(craWebpackConfigPath)(webpackConfig.mode);
415
+ logger2.info(`=> Modifying Create React App rules.`);
416
+ const craRules = await processCraConfig(craWebpackConfig, options);
417
+ const isProd = webpackConfig.mode !== "development";
418
+ const coreOptions = await options.presets.apply("core");
419
+ const builder = coreOptions?.builder;
420
+ const builderOptions = typeof builder === "string" ? {} : builder?.options;
421
+ const cacheConfig = builderOptions?.fsCache ? { cache: { type: "filesystem" } } : {};
422
+ const lazyCompilationConfig = builderOptions?.lazyCompilation && !isProd ? { experiments: { lazyCompilation: { entries: false } } } : {};
423
+ return {
424
+ ...webpackConfig,
425
+ ...cacheConfig,
426
+ ...lazyCompilationConfig,
427
+ module: {
428
+ ...webpackConfig.module,
429
+ rules: [...filteredRules || [], ...craRules]
430
+ },
431
+ // NOTE: this prioritizes the storybook version of a plugin
432
+ // when there are duplicates between SB and CRA
433
+ plugins: mergePlugins(
434
+ ...webpackConfig.plugins ?? [],
435
+ ...craWebpackConfig.plugins ?? []
436
+ ),
437
+ resolve: {
438
+ ...webpackConfig.resolve,
439
+ extensions: craWebpackConfig.resolve?.extensions,
440
+ modules: [
441
+ ...webpackConfig.resolve && webpackConfig.resolve.modules || [],
442
+ join4(REACT_SCRIPTS_PATH, "node_modules"),
443
+ ...getModulePath(CWD)
444
+ ],
445
+ plugins: [PnpWebpackPlugin],
446
+ // manual copy from builder-webpack because defaults are disabled in this CRA preset
447
+ conditionNames: [
448
+ ...webpackConfig.resolve?.conditionNames ?? [],
449
+ "storybook",
450
+ "stories",
451
+ "test",
452
+ "..."
453
+ ]
454
+ },
455
+ resolveLoader
456
+ };
457
+ }, "webpack");
458
+ var exportedCore = core;
459
+ var exportedWebpack = webpack;
460
+ export {
461
+ exportedCore as core,
462
+ exportedWebpack as webpack
463
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/preset-create-react-app",
3
- "version": "9.2.0-alpha.3",
3
+ "version": "10.0.0-beta.0",
4
4
  "description": "Storybook for Create React App preset",
5
5
  "keywords": [
6
6
  "storybook"
@@ -19,24 +19,11 @@
19
19
  "url": "https://opencollective.com/storybook"
20
20
  },
21
21
  "license": "MIT",
22
+ "type": "module",
22
23
  "exports": {
23
- ".": {
24
- "types": "./dist/index.d.ts",
25
- "node": "./dist/index.js",
26
- "import": "./dist/index.mjs",
27
- "require": "./dist/index.js"
28
- },
29
- "./preset": {
30
- "types": "./dist/index.d.ts",
31
- "node": "./dist/index.js",
32
- "import": "./dist/index.mjs",
33
- "require": "./dist/index.js"
34
- },
24
+ "./index": "./dist/index.js",
35
25
  "./package.json": "./package.json"
36
26
  },
37
- "main": "dist/index.js",
38
- "module": "dist/index.mjs",
39
- "types": "dist/index.d.ts",
40
27
  "files": [
41
28
  "dist/**/*",
42
29
  "README.md",
@@ -45,8 +32,8 @@
45
32
  "!src/**/*"
46
33
  ],
47
34
  "scripts": {
48
- "check": "jiti ../../../scripts/prepare/check.ts",
49
- "prep": "jiti ../../../scripts/prepare/bundle.ts"
35
+ "check": "jiti ../../../scripts/check/check-package.ts",
36
+ "prep": "jiti ../../../scripts/build/build-package.ts"
50
37
  },
51
38
  "dependencies": {
52
39
  "@pmmmwh/react-refresh-webpack-plugin": "^0.5.1",
@@ -61,18 +48,10 @@
61
48
  },
62
49
  "peerDependencies": {
63
50
  "react-scripts": ">=5.0.0",
64
- "storybook": "^9.2.0-alpha.3"
51
+ "storybook": "^10.0.0-beta.0"
65
52
  },
66
53
  "publishConfig": {
67
54
  "access": "public"
68
55
  },
69
- "bundler": {
70
- "entries": [
71
- "./src/index.ts"
72
- ],
73
- "formats": [
74
- "cjs"
75
- ]
76
- },
77
- "gitHead": "ce6a1e4a8d5ad69c699021a0b183df89cfc7b684"
56
+ "gitHead": "a8e7fd8a655c69780bc20b9749d2699e45beae16"
78
57
  }
package/preset.js ADDED
@@ -0,0 +1 @@
1
+ export * from './src/index.js';
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- declare const exportedCore: any;
2
- declare const exportedWebpack: any;
3
-
4
- export { exportedCore as core, exportedWebpack as webpack };