3

I'm setting a component as dynamically callable:

index.tsx

import dynamic from "next/dynamic";
import { PhoneNumberInputProps } from "./components/PhoneNumberInput";

const PhoneNumberInput = dynamic<PhoneNumberInputProps>(
  () => import("./components/PhoneNumberInput") as any
);

components/PhoneNumberInput.tsx

...
import PhoneInput from "react-phone-number-input";
...

export type PhoneNumberInputProps = {...};

export const PhoneNumberInput = ({...}: PhoneNumberInputProps) => {
...
}

So, react-phone-number-input shouldn't be part of the initial bundle, right? but when I analyze it it is still present. Why?

Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55
  • 2
    I don't agree with @juliomalves. You can remove it from the client bundle, that's the whole point of dynamic loading! I just tested it, my dynamic component is never used in the client build and is only ever imported dynamically. I believe it's not working in this case because you've imported the file for `PhoneNumberInputProps`, you can remove the import and change dynamic's input type to `any` and it should not include it in the `main.js` bundle after that. – ThomasReggi May 08 '22 at 18:22
  • @ThomasReggi You're most likely correct. I was wrong and no longer agree with my own statement either :) You should add the explanation as an answer to the question! – juliomalves May 08 '22 at 20:09

1 Answers1

2

In order to remove the file PhoneNumberInput.tsx from the bundle you need to remove the import in index.ts to ./components/PhoneNumberInput.

For PhoneNumberInputProps you can move that type to its own file, or just change the type to Any to test (if typescript is giving you a hard time).

const PhoneNumberInput = dynamic<Any>(
  () => import("./components/PhoneNumberInput")
);
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • as of typescript 3.8 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html you can use type imports, these will be removed completely from the typescript output, so in this case `import type { PhoneNumberInputProps } from "./components/PhoneNumberInput";`, and these imports shouldn't be an issue when code splitting in nextjs with dynamic imports – Kevin K. Mar 13 '23 at 10:33