Skip to content

Commit

Permalink
Use require for optional module imports
Browse files Browse the repository at this point in the history
Webpack issues a warning when trying to import() a module that is
not present, whereas it does not do so — or at least, not in a way
that blocks Next.js from building the app — with require(). Since
we're requiring a bundler anyway (since we're using npm package
names rather than import paths), we're not any worse off using a
non-standard module system for these.

For more info, see: webpack/webpack#7713
  • Loading branch information
Vinnl committed May 11, 2020
1 parent 4d2c8da commit e80382d
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions src/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,22 @@ export const fetch: typeof window.fetch = (resource, init) => {
// Implementation note: it's up to the client application to resolve these module names to the
// respective npm packages. At least one commonly used tool (Webpack) is only able to do that if
// the module names are literal strings.
const fetcherPromise = import(
// TypeScript cannot find the module - which is correct, since the consumer app should/can
// provide it:
// @ts-ignore
"@inrupt/solid-auth-fetcher"
)
.catch(() =>
import(
// TypeScript cannot find the module - which is correct, since the consumer app should/can
// provide it:
// @ts-ignore
"solid-auth-client"
)
)
.catch(() => import("cross-fetch"));
// Additionally, Webpack throws a warning in a way that halts compilation for at least Next.js
// when using native Javascript dynamic imports (`import()`), whereas `require()` just logs a
// warning. Since the use of package names instead of file names requires a bundles anyway, this
// should not have any practical consequences. For more background, see:
// https://github.com/webpack/webpack/issues/7713
let fetch;

return fetcherPromise.then(({ fetch }) => fetch(resource, init));
try {
fetch = require("@inrupt/solid-auth-fetcher").fetch;
} catch (e) {
try {
fetch = require("solid-auth-client").fetch;
} catch (e) {
fetch = require("cross-fetch");
}
}

return fetch(resource, init);
};

0 comments on commit e80382d

Please sign in to comment.