Idiomatic example with Next.js & TypeScript #1236
-
Hi https://github.com/vercel/next.js/tree/canary/examples/with-msw I try to do something like #1227 (comment) for TypeScript. I wanted to do something like:
import { AppProps } from "next/app";
void (async function initMocks() {
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
await import(/* webpackChunkName: "msw-mocks" */ "../mocks");
}
})();
export default function App({ Component, pageProps }: AppProps) {
return (
<Component {...pageProps} />
);
} and async function initMocks() {
if (typeof window === "undefined") {
const { server } = await import(
/* webpackChunkName: "msw-server" */
"./server"
);
server.listen();
} else {
const { worker } = await import(
/* webpackChunkName: "msw-browser" */
"./browser"
);
await worker.start();
}
}
void initMocks()
export {} When I try i - I get those MSW chunks in the bundle too (splitted to chunks) Currently what I end up with is import { AppProps } from "next/app";
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
require("../mocks");
}
export default function App({ Component, pageProps }: AppProps) {
return (
<Component {...pageProps} />
);
} and if (typeof window === "undefined") {
module,@typescript-eslint/no-unsafe-assignment
const { server } = require("./server");
server.listen();
} else {
module,@typescript-eslint/no-unsafe-assignment
const { worker } = require("./browser");
worker.start();
}
export {}; And it works well (without adding msw to the bundle) Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @nirtamir2. I believe your question is related to how to include MSW conditionally with That's the main reason we recommend using // Note that unconditional type imports are fine.
import type { SetupWorkerApi } from 'msw'
import type { SetupServerApi } from 'msw/node'
// ...your conditions
const server: SetupServerApi = require('./server').server
// ..and then a similar thing for the worker
const worker: SetupWorkerApi = require('./worker').worker Otherwise, there isn't much I can recommend. |
Beta Was this translation helpful? Give feedback.
Hey, @nirtamir2.
I believe your question is related to how to include MSW conditionally with
import
statements. I don't think you can, as modern bundlers extract those statements at build time. I'm not aware if conditional imports are possible, so you will get anything you import that way in your bundle regardless if there's a condition before the import that'd prevent it.That's the main reason we recommend using
require
, as dependencies included that way are not statically analyzable. You can annotate the imported objects in TypeScript to keep type safety: