Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Csf Tools: Fix overriding scalar named export values #21190

Merged
merged 1 commit into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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