-
-
Notifications
You must be signed in to change notification settings - Fork 534
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: keep
graphql
import as require in cjs (#2258)
- Loading branch information
1 parent
0bc6b3f
commit b977602
Showing
3 changed files
with
44 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import fs from 'fs/promises' | ||
import type { Plugin } from 'esbuild' | ||
|
||
/** | ||
* A plugin to replace `require('graphql')` statements with `await import('graphql')` | ||
* only for ESM bundles. This makes the GraphQL module to be imported lazily | ||
* while maintaining the CommonJS compatibility. | ||
* @see https://github.com/mswjs/msw/issues/2254 | ||
*/ | ||
export function graphqlImportPlugin(): Plugin { | ||
return { | ||
name: 'graphql-import-plugin', | ||
setup(build) { | ||
if (build.initialOptions.format !== 'esm') { | ||
return | ||
} | ||
|
||
build.onLoad({ filter: /\.ts$/ }, async (args) => { | ||
const contents = await fs.readFile(args.path, 'utf-8') | ||
const match = /require\(['"]graphql['"]\)/g.exec(contents) | ||
|
||
if (match) { | ||
return { | ||
loader: 'ts', | ||
contents: | ||
contents.slice(0, match.index - 1) + | ||
`await import('graphql').catch((error) => {console.error('[MSW] Failed to parse a GraphQL query: cannot import the "graphql" module. Please make sure you install it if you wish to intercept GraphQL requests. See the original import error below.'); throw error})` + | ||
contents.slice(match.index + match[0].length), | ||
} | ||
} | ||
}) | ||
}, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters