Skip to content

Commit

Permalink
Allow exporting ESM
Browse files Browse the repository at this point in the history
This adds an option esm which if set to true changes the exports
to use ESM format

export default doc;

export const MyQuery = doc;

etc.

This allows usage with [node-esm-loader](npm.im/node-esm-loader)

```js
export default {
  loaders: [
    {
      test: /\.(graphql|gql)$/,
      use: [
        {
          loader: "graphql-tag/loader.js",
          options: {
            esm: true
          }
        }
      ]
    },
  ],
};
```
  • Loading branch information
mkg20001 committed Dec 11, 2023
1 parent eeb670e commit 5265cad
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ function expandImports(source, doc) {

module.exports = function(source) {
this.cacheable();
// can be simplified later to this.options?.esm
// options is optional here as that breaks where a fake webpack context is used
// that doesn't have options
const esm = (this.options || {}).esm;
const doc = gql`${source}`;
let headerCode = `
var doc = ${JSON.stringify(doc)};
Expand All @@ -63,7 +67,7 @@ module.exports = function(source) {

if (operationCount < 1) {
outputCode += `
module.exports = doc;
${esm ? "export default doc;" : "module.exports = doc;"}
`
} else {
outputCode += `
Expand Down Expand Up @@ -162,8 +166,8 @@ module.exports = function(source) {
return newDoc;
}
module.exports = doc;
${esm ? "export default doc;" : "module.exports = doc;"}
`

for (const op of doc.definitions) {
Expand All @@ -178,7 +182,7 @@ module.exports = function(source) {

const opName = op.name.value;
outputCode += `
module.exports["${opName}"] = oneQuery(doc, "${opName}");
${esm ? `export const ${opName}` : `module.exports[${JSON.stringify(opName)}]`} = oneQuery(doc, ${JSON.stringify(opName)});
`
}
}
Expand Down

0 comments on commit 5265cad

Please sign in to comment.