Skip to content

Commit a4b4916

Browse files
committed
Allow exporting ESM
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 } } ] }, ], }; ```
1 parent 9f1cffe commit a4b4916

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

loader.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ function expandImports(source, doc) {
4242

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

6468
if (operationCount < 1) {
6569
outputCode += `
66-
module.exports = doc;
70+
${esm ? "export default doc;" : "module.exports = doc;"}
6771
`
6872
} else {
6973
outputCode += `
@@ -162,8 +166,8 @@ module.exports = function(source) {
162166
163167
return newDoc;
164168
}
165-
166-
module.exports = doc;
169+
170+
${esm ? "export default doc;" : "module.exports = doc;"}
167171
`
168172

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

179183
const opName = op.name.value;
180184
outputCode += `
181-
module.exports["${opName}"] = oneQuery(doc, "${opName}");
185+
${esm ? `export const ${opName}` : `module.exports[${JSON.stringify(opName)}]`} = oneQuery(doc, ${JSON.stringify(opName)});
182186
`
183187
}
184188
}

0 commit comments

Comments
 (0)