From cb2964e51a2cc32a26ffc9fe007d03d65cfde13b Mon Sep 17 00:00:00 2001 From: Jonathan Glanz Date: Tue, 19 Nov 2024 10:36:15 -0500 Subject: [PATCH] Added configuration code that scours the current file path and working directory tree for an `.swcrc` config file. If it finds one then it loads that file from disk and takes precidence over the code config --- src/preset.ts | 61 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 43 insertions(+), 18 deletions(-) diff --git a/src/preset.ts b/src/preset.ts index 74d4112..e4e3619 100644 --- a/src/preset.ts +++ b/src/preset.ts @@ -1,3 +1,5 @@ +import Path from "path"; +import Fs from "fs"; import { getProjectRoot } from "@storybook/core-common"; import type { Options } from "@storybook/types"; import type { Options as SwcOptions } from "@swc/core"; @@ -8,6 +10,24 @@ const virtualModuleFiles = [ /storybook-stories\.js$/, ]; +function findSWCConfigFile() { + const basePaths = [process.cwd(), Path.resolve(__dirname)]; + for (const basePath of basePaths) { + const pathParts = basePath.split(/[\\\/]/); + while (pathParts.length) { + const dir = Path.join(...pathParts); + const file = Path.join(dir, ".swcrc"); + if (Fs.existsSync(file)) { + return file; + } + + pathParts.pop(); + } + } + + return null; +} + export const webpackFinal = async (config: Configuration, options: Options) => { const swcOptions = await options.presets.apply("swc", {}, options); const typescriptOptions = await options.presets.apply( @@ -16,24 +36,29 @@ export const webpackFinal = async (config: Configuration, options: Options) => { options, ); - const swcFinalOptions: SwcOptions = { - ...swcOptions, - env: { - ...(swcOptions?.env ?? {}), - // Transpiles the broken syntax to the closest non-broken modern syntax. - // E.g. it won't transpile parameter destructuring in Safari - // which would break how we detect if the mount context property is used in the play function. - bugfixes: swcOptions?.env?.bugfixes ?? true, - }, - jsc: { - ...(swcOptions.jsc ?? {}), - parser: swcOptions.jsc?.parser ?? { - syntax: "typescript", - tsx: true, - dynamicImport: true, - }, - }, - }; + const swcConfigFile: string | null = findSWCConfigFile(); + + const swcFinalOptions: SwcOptions = + !!swcConfigFile && Fs.existsSync(swcConfigFile) + ? JSON.parse(Fs.readFileSync(swcConfigFile, "utf-8")) + : { + ...swcOptions, + env: { + ...(swcOptions?.env ?? {}), + // Transpiles the broken syntax to the closest non-broken modern syntax. + // E.g. it won't transpile parameter destructuring in Safari + // which would break how we detect if the mount context property is used in the play function. + bugfixes: swcOptions?.env?.bugfixes ?? true, + }, + jsc: { + ...(swcOptions.jsc ?? {}), + parser: swcOptions.jsc?.parser ?? { + syntax: "typescript", + tsx: true, + dynamicImport: true, + }, + }, + }; config.module = { ...(config.module || {}),