Client components in turborepo cause error

1.4k views Asked by At

I am trying to build a Turborepo with react client components in a separate internal ui package.

Unfortunately, tsup removes the use client directive at the top of the ui packages, which are needed for nextjs. Message:

Module level directives cause errors when bundled, "use client" in "dist/Test.mjs" was ignored.

Minimal reproduction sandbox, showing the error: https://shorturl.at/noxzI

Any tips on how to fix this?


EDIT 1:

New URL: https://rb.gy/gubwk


EDIT 2:

The above minimal repo produces the following error message:

TypeError: a.default.createContext is not a function

Based on other SO answers, that is likely because use client is missing. If you add use client to the built Test chunk in the dist folder, that error goes away and is replaced by this error:

TypeError: styled_components__WEBPACK_IMPORTED_MODULE_2__.div is not a function


EDIT 3:

Just a side-note that the error happens regardless of whether the component is a js file (e.g. Test) or a tsx file (e.g. Card). Somehow webpack does not include the styled-component package.

1

There are 1 answers

3
Adam On
  1. Delete the dist folder in the ui package.
  2. Edit your /packages/ui/tsup.config.js file with the following:
    import { defineConfig, Options } from "tsup";
    
    export default defineConfig((options: Options) => ({
      banner: {
        js: `"use client"`,
      },
      // treeshake: true,
      splitting: true,
      entry: ["./**/*.tsx"],
      format: ["esm"],
      dts: true,
      minify: true,
      clean: true,
      external: ["react"],
      ...options,
    }));

Note the banner option telling tsup to not remove the "use client", and I noticed that treeshake was removing "too much" so you can delete/remove that option. With the following config I was able to build the project without any errors.

  1. run build script again!