Skip to content

Commit

Permalink
Merge pull request #21190 from storybookjs/shilman/csf-tools-fix-conf…
Browse files Browse the repository at this point in the history
…igfile-named-export-scalars

Csf Tools: Fix overriding scalar named export values
  • Loading branch information
shilman authored Feb 21, 2023
2 parents 92ca732 + 9f6c51b commit 7e68aa2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
11 changes: 11 additions & 0 deletions code/lib/csf-tools/src/ConfigFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions code/lib/csf-tools/src/ConfigFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ export class ConfigFile {

_exports: Record<string, t.Expression> = {};

// 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<string, t.VariableDeclarator> = {};

_exportsObject: t.ObjectExpression | undefined;

_quotes: 'single' | 'double' | undefined;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit 7e68aa2

Please sign in to comment.