Skip to content

Commit

Permalink
Fixed emitLegacyCommonJSImports in getImports adding JS when truthy r… (
Browse files Browse the repository at this point in the history
  • Loading branch information
charle692 committed Jan 18, 2023
1 parent 884d25c commit a981985
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/unlucky-suits-pay.md
@@ -0,0 +1,5 @@
---
'@graphql-codegen/visitor-plugin-common': patch
---

Fix issue where visitor-plugin-common emitted ESM imports for Operations when emitLegacyCommonJSImports is true
Expand Up @@ -532,7 +532,7 @@ export class ClientSideBaseVisitor<
if (this._collectedOperations.length > 0) {
if (this.config.importDocumentNodeExternallyFrom === 'near-operation-file' && this._documents.length === 1) {
let documentPath = `./${this.clearExtension(basename(this._documents[0].location))}`;
if (this.config.emitLegacyCommonJSImports) {
if (!this.config.emitLegacyCommonJSImports) {
documentPath += '.js';
}

Expand Down
@@ -0,0 +1,85 @@
import { buildSchema, OperationDefinitionNode, parse } from 'graphql';
import { ClientSideBaseVisitor, DocumentMode } from '../src/client-side-base-visitor.js';

describe('getImports', () => {
describe('when documentMode "external", importDocumentNodeExternallyFrom is "near-operation-file"', () => {
const schema = buildSchema(/* GraphQL */ `
type Query {
a: A
}
type A {
foo: String
bar: String
}
`);

describe('when emitLegacyCommonJSImports is true', () => {
it('does not append `.js` to Operations import path', () => {
const fileName = 'fooBarQuery';
const importPath = `src/queries/${fileName}`;

const document = parse(
`query fooBarQuery {
a {
foo
bar
}
}
`
);

const visitor = new ClientSideBaseVisitor(
schema,
[],
{
emitLegacyCommonJSImports: true,
importDocumentNodeExternallyFrom: 'near-operation-file',
documentMode: DocumentMode.external,
},
{},
[{ document, location: importPath }]
);

visitor.OperationDefinition(document.definitions[0] as OperationDefinitionNode);

const imports = visitor.getImports();
expect(imports[0]).toBe(`import * as Operations from './${fileName}';`);
});
});

describe('when emitLegacyCommonJSImports is false', () => {
it('appends `.js` to Operations import path', () => {
const fileName = 'fooBarQuery';
const importPath = `src/queries/${fileName}`;

const document = parse(
`query fooBarQuery {
a {
foo
bar
}
}
`
);

const visitor = new ClientSideBaseVisitor(
schema,
[],
{
emitLegacyCommonJSImports: false,
importDocumentNodeExternallyFrom: 'near-operation-file',
documentMode: DocumentMode.external,
},
{},
[{ document, location: importPath }]
);

visitor.OperationDefinition(document.definitions[0] as OperationDefinitionNode);

const imports = visitor.getImports();
expect(imports[0]).toBe(`import * as Operations from './${fileName}.js';`);
});
});
});
});

0 comments on commit a981985

Please sign in to comment.