From 9f6c51b41fcbff3301abda82f989e3c34ccf5bb6 Mon Sep 17 00:00:00 2001 From: Michael Shilman Date: Wed, 22 Feb 2023 01:29:43 +0800 Subject: [PATCH] Csf Tools: Fix overriding scalar named export values --- code/lib/csf-tools/src/ConfigFile.test.ts | 11 +++++++++++ code/lib/csf-tools/src/ConfigFile.ts | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/code/lib/csf-tools/src/ConfigFile.test.ts b/code/lib/csf-tools/src/ConfigFile.test.ts index 6b4d6ce6e111..565d28c3f940 100644 --- a/code/lib/csf-tools/src/ConfigFile.test.ts +++ b/code/lib/csf-tools/src/ConfigFile.test.ts @@ -262,6 +262,17 @@ describe('ConfigFile', () => { }; `); }); + it('found top-level scalar', () => { + expect( + setField( + ['foo'], + 'baz', + dedent` + export const foo = 'bar'; + ` + ) + ).toMatchInlineSnapshot(`export const foo = 'baz';`); + }); it('found object', () => { expect( setField( diff --git a/code/lib/csf-tools/src/ConfigFile.ts b/code/lib/csf-tools/src/ConfigFile.ts index 6f8edd6604a8..4c1fbee79aeb 100644 --- a/code/lib/csf-tools/src/ConfigFile.ts +++ b/code/lib/csf-tools/src/ConfigFile.ts @@ -113,6 +113,11 @@ export class ConfigFile { _exports: Record = {}; + // FIXME: this is a hack. this is only used in the case where the user is + // modifying a named export that's a scalar. The _exports map is not suitable + // for that. But rather than refactor the whole thing, we just use this as a stopgap. + _exportDecls: Record = {}; + _exportsObject: t.ObjectExpression | undefined; _quotes: 'single' | 'double' | undefined; @@ -172,6 +177,7 @@ export class ConfigFile { exportVal = _findVarInitialization(exportVal.name, parent as t.Program) as any; } self._exports[exportName] = exportVal; + self._exportDecls[exportName] = decl; } }); } else { @@ -268,6 +274,9 @@ export class ConfigFile { this._exports[path[0]] = expr; } else if (exportNode && t.isObjectExpression(exportNode) && rest.length > 0) { _updateExportNode(rest, expr, exportNode); + } else if (exportNode && rest.length === 0 && this._exportDecls[path[0]]) { + const decl = this._exportDecls[path[0]]; + decl.init = _makeObjectExpression([], expr); } else if (this.hasDefaultExport) { // This means the main.js of the user has a default export that is not an object expression, therefore we can't change the AST. throw new Error(